I've been browsing the source code of Rails, and find a number of uses of delegate
. What does this do and how does it work?
here is the official explanation:
delegate(*methods) public
Provides a delegate class method to easily expose contained objects’ public methods as your own.
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>
here's some other explanations of how it works with examples:
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With