Rails uses object oriented concetps?

As i have understood rails 6, it use object oriented concept’s in it’s implementation like.

  1. single table inheritance = inheritance concept’s

  2. polymorphic association = polymorphism concept’s

  3. AR callbacks with private method = encapsulation concept’s

can anyone say more point on this. thanks

What are you looking for?

Ruby is an almost pure OO language - the closest thing I’ve found to Smalltalk, which is a truly pure OO language.

In Smalltalk there are no keywords, only punctuation. Classes are defined by sending messages to objects. Message receivers are defined by sending message to objects. Everything is either an object or a message - and that to me is the essence of an OO language.

Inheritance is an implementation detail - you can have OO languages without inheritance. Polymorphism is a language feature that comes from dynamic typing. Encapsulation is a design choice. In Smalltalk, all methods are public, all variables are private. Encapsulation comes from a doctrine known as “Tell, Don’t Ask” - if you want an object to do something, you tell it what to do, instead of asking it for its internal data and then acting on it.

In Ruby it’s pretty similar, but there are keywords and some simple types (but those are also represented as objects). However, you can also use Ruby as you would Smalltalk (for example you can define a class by using a “class MyClass … end” definition or you can call “Class.new do … end”.

Rails is built on top of Ruby - so therefore is built in an OO style. However, databases are not OO and the HTTP interface is not OO. So Rails apps have a router object that instantiates a controller that handles each incoming request. The controller can choose to access models - that represent database rows - and use those to render views - that outputs HTML (or JSON or some other format).

All of these are built using ruby objects and classes.

However, ActiveRecord, the set of classes that manage the interface with a relational database, is what is called an Object-Relational Mapper. Because relational databases are not OO, a mapping layer is needed. ActiveRecord has added single table inheritance and polymorphism. But by definition, ActiveRecord is “ask, don’t tell” - so the model object reveals its data to the world and then the world (usually the views) choose how to represent that.

Likewise, a controller is little more than a series of public functions within a namespace - there’s nothing particularly OO about them.

So, while Ruby is very OO, Rails is very pragmatic about where to use OO and where to bypass it.

(Sorry, got a bit theoretical there)

2 Likes