Rails のデリゲートとは何ですか?
概要
Rails のソースコードを閲覧していると、デリゲートの使用法が多数見つかりました。これは何をするもので、どのように機能するのでしょうか?
解決策
公式の説明は次のとおりです。
class Greeter < ActiveRecord::Base
def hello
'hello'
end
def goodbye
'goodbye'
end
end
class Foo < ActiveRecord::Base
belongs_to :greeter
delegate :hello, to: :greeter
end
Foo.new.hello # => "hello"
Foo.new.goodbye # => NoMethodError: undefined method `goodbye' for #<Foo:0x1af30c>
これがどのように機能するかを例を挙げて説明します。
http://brettu.com/rails-daily-ruby-tip-20-use-the-delegate-method-in-rails-to-reduce-code/
http://www.simonecarletti.com/blog/2009/12/inside-ruby-on-rails-delegate/
http://pivotallabs.com/rails-delegates-are-even-more-useful-than-i-knew/