Tbpgr Blog

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

Ruby | Module | append_features

概要

Module#append_features(module_or_class) -> self

詳細

モジュール or クラスに self の機能を追加します。
このメソッドは Module#include の実体である。

サンプルコード

include 直前に乱数を生成して結果によって include を継続するかどうか判断する。

module Hogeable
  def hogeable
    'hogeable'
  end

  def self.append_features(module_or_class)
    puts "Include #{module_or_class}. maybe."
    return if rand(2) == 0
    super
  end
end

class Hoge
  include Hogeable
end

hoge = Hoge.new
puts hoge.hogeable if hoge.respond_to?(:hogeable)

出力

ランダムにメソッドが include される

$ ruby hoge.rb
Include Hoge. maybe.
hogeable
$ ruby hoge.rb
Include Hoge. maybe.
hogeable
$ ruby hoge.rb
Include Hoge. maybe.
hogeable
$ ruby hoge.rb
Include Hoge. maybe.
$ ruby hoge.rb
Include Hoge. maybe.
hogeable
$ ruby hoge.rb
Include Hoge. maybe.
hogeable