Reputation: 751
module ProductsHelper
attr_reader :products, :product
end
What is the outcome of doing the above? I saw this in Rails guide, and just don't understand.
Upvotes: 2
Views: 1609
Reputation: 3935
This is a Ruby convention which creates a "getter" called product and another called products.
For example if you had an object ph which is equivalent to ProductHelper.new.
ph = ProductHelper.new
And within that module there exists an instance variable.
def initialize
@products = "awesomeness"
end
You wouldn't be able to access it without doing a send on the module as it would be considered private to that instance of ph.
(Don't worry if the following is confusing as its not something you'll see much as a newcomer to rails. You'll see it more when you get into meta programming.)
ProductsHelper.send :products
However an attr_reader would allow you to read the method or variable as if it were an attribute of the instance.
ProductHelper.products
It essentially does this piece of code for you.
def products
@products # which is an instance variable within the instantiated object.
end
Although you'll usually only see these in your model classes not in Modules ... since all classes in Ruby are modules though, this behavior exists at that level too. If you don't have any methods then would return information then calling .products would only return nil.
In Ruby, there are also attr_writers which create "setters" too.
def products( value )
@products = value
end
Which allow you to do this.
ph.products = "some awesome thing"
Lastly you also have the attr_accessor which creates both a getter and setter in one action.
Upvotes: 3
Reputation: 451
It will allow to read values from @products
and @product
instance variables by calling products
and product
in the view. You still need to set them in controller.
These readers dont realy do much of a help.
Upvotes: 2