Ruby on Rails and the Law of Demeter design Principle.

In my coursework for learning Ruby on Rails, a simple design priciple was brought to my attention. It is called the Law of Demeter. As it turn out Demeter is a the Greek goddess of Agriculture, Fertility, and the Harvest. If ound a brief description as to why this design principle was named for the Greek goddess of agriculture.

The Greek goddess of Agrigulture.
The Demeter project was named after Demeter because we were working on a hardware description language Zeus and we were looking for a tool to simplify the implementation of Zeus. We were looking for a tool name related to Zeus and we chose a sister of Zeus: Demeter.
Later we promoted the idea that Demeter-style software development is about growing software as opposed to building software.
-What is Demeter?
link here

So what is the Law of Demeter (LoD) and and how can adhere to it?

I’m sure by you are familiar with ActiveRecord it’s association methods allow you to use dot notation to access methods and attributes across associating classes.

EXAMPLE:

Say we had a many-to-many relationship between a Driver and Passenger through Rides.

class Driver < ActiveRecord::Base
has_many :rides
has_many :passengers, through: :rides
end
class Ride < ActiveRecord::Base
belongs_to :driver
belongs_to :passenger
end
class Passenger < ActiveRecord::Base
has_many :rides
has_many :drivers, through: :rides
end

We would then be able to access information across models by chaining together methods such as:

@driver.passegers.all

Using several dots is a violation of of the Law of Demeter which would have us use only one.
But how would we achieve this?

We would need to create a helper method in the Driver class that would achieve this for us.

class Driver < ActiveRecord::Base
has_many :rides
has_many :passengers, through: :rides
def all_passengers
self.passengers.all
end

end

Now were would be able to adhere to the design priciple by only having to use one dot to access the same information.

@driver.all_passengers

Ruby, iOS