Ruby: What does the module included in the method mean?

I know that a module can be included in a class or another module. But I saw here that the module is included in the method . What does it mean?

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
+5
source share
1 answer

In this case, a specific method should be called at the class level, for example:

class Foo
    include ActsAsVotable
    acts_as_votable
end

Ruby has this wonderful / terrible (depending on who you ask) that you can dynamically define for the class. Here, the method acts_as_votablefirst calls has_many(which adds several mthods to the class Foo), and then adds the method cast_voteto the class Foothrough include InstanceMethods.

So you get the equivalent:

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
+4
source

All Articles