Search code examples
rubymodulemetaprogrammingmixins

self.included in a module


I have a class Brand that includes a module SimpleURLSanitizer. The module has a class method defined as below:

class Brand
  include SimpleURLSanitizer
end

module SimpleURLSanitizer
  def self.included base
    base.send :extend, self
  end
end

Since we are including the module, it will only have access to the module's instance methods. But the class method included will be called when the module is included in the class. The base is the Brand class. What is this included method doing? Is the self inside this method referring to the module or the Brand class? How does it work?


Solution

  • As you're including SimpleURLSanitizer in a class, all the methods of SimpleURLSanitizer will be accessible as instance method. This is the default behavior.

    The included part is also making sure that, you can access those methods as class methods.