Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: What does module included in a method means?

Tags:

module

ruby

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
like image 366
Misha Moroshko Avatar asked Oct 14 '22 18:10

Misha Moroshko


1 Answers

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
like image 169
DarkDust Avatar answered Dec 30 '22 05:12

DarkDust