4

I see this pattern a lot:

module Article::Score

    def self.included(base)
        base.send :extend, ClassMethods
        base.send :include, InstanceMethods
    end

    module ClassMethods
    ...
    end

    module InstanceMethods
    ...
    end
end

Then in the article model, I see this

class Article
   include Article::Score
   ...
end

so my guess is that "base" probably refers to the article class and we're just including the instance methods and extending the class methods. But can someone explain the snippet "self.included(base)" and give an overview of what's going on there?

2
  • 'included' is one Ruby's several 'callback' (aka 'hook') methods. You'll need to add these to your arsenal, not just admire their use by the clever ones. Another is 'inherited', something every parent needs: notification that it has another child to look after. In his book, "Eloquent Ruby" (p. 249), Russ Olsen gives the example of a DocumentReader class, with one subclass for each type of document (text, XML, YAML,..). By using inherited, no change is need to the parent's code when a new child is born (or leaves home). Oct 25, 2013 at 22:14
  • The relevant page in the spec (for Ruby 2.7.0) is here: docs.ruby-lang.org/en/2.7.0/Module.html#method-i-included. The argument (which needn't be called base) is the module/class in which the module is being included.
    – Sam
    Nov 18, 2021 at 12:47

1 Answer 1

8

The self.included function is called when the module is included. It allows methods to be executed in the context of the base (where the module is included).

1
  • But why include the include those modules in such a round-about way?
    – BenKoshy
    Mar 3, 2020 at 21:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.