Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | Module | included

概要

Module#included(class_or_module) -> ()

詳細

self が Module#include されたときに対象のクラスまたはモジュールを引数にしてインタプリタがこのメソッドを呼び出す。

このメソッドをオーバーライドすることで、モジュールの include 時に任意の処理を実行できる。

サンプルコード
module Hogeable
  def hogeable
    puts 'hogeable'
  end

  def self.included(class_or_module)
    puts 'start included'
    class_or_module.send(:define_method, :included_method) do |*args|
      print "included", "-", "args = ", args, "\n"
    end
    puts 'end included'
  end
end

class Hoge
  include Hogeable
end

hoge = Hoge.new
hoge.hogeable
hoge.included_method(:hoge, :hige, :hage)

出力

$ ruby included.rb
start included
end included
hogeable
included-args = [:hoge, :hige, :hage]