I know that a module can be included in a class or another module. But, I saw here that a module is included in a method. What do this means ?
module ActsAsVotable
module ClassMethods
def acts_as_votable
has_many :votes, :as => :votable, :dependent => :delete_all
include InstanceMethods # What does this means ??
end
end
module InstanceMethods
def cast_vote( vote )
Vote.create( :votable => self, :up => vote == :up )
end
end
end
In this case, the defined method is meant to be called at the class level, like this:
class Foo
include ActsAsVotable
acts_as_votable
end
Ruby has this wonderful/horrible (depends on who you ask) feature that you can dynamically define a class. Here, the acts_as_votable
method first calls has_many
(which adds a few mthods to the class Foo
) and then adds the cast_vote
method to the Foo
class through the include InstanceMethods
.
So, you end up with the equivalent of:
class Foo
# Will add further methods.
has_many :votes, :as => :votable, :dependent => :delete_all
# include InstanceMethods
def cast_vote( vote )
Vote.create( :votable => self, :up => vote == :up )
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With