0
0
Rubyprogramming~5 mins

Included hook in Ruby

Choose your learning style9 modes available
Introduction

The included hook runs code automatically when a module is added to a class. It helps set up things right away without extra steps.

When you want to add methods or variables to a class as soon as a module is included.
When you need to run setup code automatically for classes using your module.
When you want to add class-level methods or extend behavior on inclusion.
When you want to keep your code organized by separating setup logic inside the module.
Syntax
Ruby
module MyModule
  def self.included(base)
    # code to run when included
  end
end

The included method is a class method of the module.

The base parameter is the class that includes the module.

Examples
This prints a message when the module is included in the Person class.
Ruby
module Greetings
  def self.included(base)
    puts "Greetings module included in #{base}!"
  end
end

class Person
  include Greetings
end
This adds a class method track to Device when Tracker is included.
Ruby
module Tracker
  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    def track
      puts "Tracking started"
    end
  end
end

class Device
  include Tracker
end

Device.track
Sample Program

This program shows how the included hook prints a message and adds a class method log to Application.

Ruby
module Logger
  def self.included(base)
    puts "Logger included in #{base}"
    base.extend(ClassMethods)
  end

  module ClassMethods
    def log(message)
      puts "LOG: #{message}"
    end
  end
end

class Application
  include Logger
end

Application.log("App started")
OutputSuccess
Important Notes

The included hook runs only once per class when the module is included.

You can use base.extend inside included to add class methods.

This hook helps keep your modules flexible and easy to reuse.

Summary

The included hook runs code automatically when a module is included in a class.

It receives the class as a parameter to customize behavior.

Use it to add methods or setup code without extra steps.