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>
2条答案
按热度按时间ffx8fchx1#
下面是official explanation:
delegate(* method)public
提供一个委托类方法,以方便地将所包含对象的公共方法公开为您自己的方法。
这里有一些其他的解释,它是如何工作的例子:
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/
06odsfpq2#
代理帮助您保持在LoD范围内,而不会破坏SRP。
http://en.wikipedia.org/wiki/Law_of_Demeter