Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are delegates in Rails?

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?

like image 462
Senjai Avatar asked Aug 31 '25 02:08

Senjai


1 Answers

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/

like image 100
dax Avatar answered Sep 02 '25 16:09

dax