Ruby modules – included do end block

Here’s a practical example.

class MyClass
  include MyModule
end

When you will include the module in a class, the included hook will be called. Therefore, second_class_method will be called within the scope of Class.

What happens here is

  1. first_method and second_method are included as instance-methods of MyClass.

    instance = MyClass.new
    instance.first_method
    # => whatever returned value of first_method is
    
  2. The methods of ClassMethods are automatically mixed as class methods of MyClass. This is a common Ruby pattern, that ActiveSupport::Concern encapsulates. The non-Rails Ruby code is

    module MyModule
      def self.included(base)
        base.extend ClassMethods
      end
    
      module ClassMethods
        def this_is_a_class_method
        end
      end
    end
    

    Which results in

    MyClass.this_is_a_class_method
    

    or in your case

    MyClass.first_class_method
    
  3. included is a hook that is effectively to the following code

    # non-Rails version
    module MyModule
      def self.included(base)
        base.class_eval do
          # somecode
        end
      end
    end
    
    # Rails version with ActiveSupport::Concerns
    module MyModule
      included do
        # somecode
      end
    end
    

    It’s mostly “syntactic sugar” for common patterns. What happens in practice, is that when you mix the module, that code is executed in the context of the mixer class.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)