extend
In the previous section, we learned about including methods from a module for instances of a class using the include
keyword. Modules can also be used to add class methods to a class. This can be accomplished by using the extend
keyword.
Consider the following example:
module HelperMethods def attributes_for_json [:id, :name, :created_at] end end class User extend HelperMethods end class Company extend HelperMethods end irb(main):014:0> User.attributes_for_json => [:id, :name, :created_at] irb(main):015:0> Company.attributes_for_json => [:id, :name, :created_at]
Here, we've defined a module called HelperMethods
, which defines a single method called attributes_for_json
. The intention is that these are a common set of attributes that will be used to convert objects into JSON. Because these attributes are global, in the sense that they apply to all objects, this method should be defined...