Tbpgr Blog

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

ActiveSupport | Module#delegate

概要

Module#delegate

詳細

Module#delegate について

Module#delegate

メソッドの委譲を行う。
複数メソッドの一括委譲も可能。

toオプションで委譲オブジェクトの指定
prefixオプションでプリフィックスの有無を設定(省略するとプリフィックスなし)
allow_nilオプションで委譲対象のオブジェクトがnilだった場合に、各メソッドnilを返却するかどうかを設定。
allow_nilがfalseもしくは指定無しの場合はNoMethodErrorが発生する。

サンプル

# encoding: utf-8
require 'active_support/core_ext/module/delegation'
require 'tbpgr_utils'
require 'attributes_initializable'

class Hoge
  def hoge
    "hoge"
  end
  def hige
    "hige"
  end
  def hage
    "hage"
  end
end

class HogeUser1
  include AttributesInitializable
  attr_accessor_init :hoge_klass
  delegate :hoge, :hige, to: :hoge_klass
end

hoge = HogeUser1.new(hoge_klass: Hoge.new)
bulk_puts_eval binding, <<-EOS
hoge.my_methods
hoge.hoge
hoge.hige
EOS
# p hoge.hage # => hageは委譲していないので呼び出せない

class HogeUser2
  include AttributesInitializable
  attr_accessor_init :hoge_klass
  delegate :hoge, :hige, to: :hoge_klass, prefix: true
end

hoge = HogeUser2.new(hoge_klass: Hoge.new)
bulk_puts_eval binding, <<-EOS
hoge.my_methods
hoge.hoge_klass_hoge
hoge.hoge_klass_hige
EOS

class HogeUser3
  include AttributesInitializable
  attr_accessor_init :hoge_klass
  delegate :hoge, :hige, to: :hoge_klass, allow_nil: true
end

hoge = HogeUser3.new(hoge_klass: nil)
bulk_puts_eval binding, <<-EOS
hoge.my_methods
hoge.hoge
hoge.hige
EOS

__END__
下記はTbpgrUtils gemの機能

AttributesInitializable
attr_accessor_init
bulk_puts_eval
my_methods

詳しくは下記参照
https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils

出力

hoge.my_methods # => [:hoge_klass, :hoge_klass=, :hoge, :hige, :initialize]
hoge.hoge # => "hoge"
hoge.hige # => "hige"
hoge.my_methods # => [:hoge_klass, :hoge_klass=, :hoge_klass_hoge, :hoge_klass_hige, :initialize]
hoge.hoge_klass_hoge # => "hoge"
hoge.hoge_klass_hige # => "hige"
hoge.my_methods # => [:hoge_klass, :hoge_klass=, :hoge, :hige, :initialize]
hoge.hoge # => nil
hoge.hige # => nil

コードリーディング

delegationのコードを読んで可変長の配列を引数をとりつつオプション指定も使いたい場合の参考になった。
詳しくは下記にまとめました。

可変長のリストとオプション(ハッシュ)の引数を共存させる場合
http://d.hatena.ne.jp/tbpg/20140127/1390829523