Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby: delegate if object responds to method

I'd like to use delegation in Ruby, but I can't guarantee that the target object responds to all method I will call. May I define delegation with a default behaviour?

E.g.

class DummyPresenter
  delegate :name, :age, :to => :@content, :default => nil
  def initialize(content)
    @content = content
  end
end

class Student
  def name
    "name"
  end
end    

> DummyPresenter.new(Student.new).age # => nil
> DummyPresenter.new(Student.new).name # => "name"

Now, the above example would raise:

NoMethodError:
   undefined method `age' for #<Student:0xa121212>
like image 336
mrzasa Avatar asked Jun 08 '26 01:06

mrzasa


1 Answers

def method_missing(method, *args)
  if @content.respond_to? method
    @content.send method, *args
  else
    #your default behaviour (or super)
  end 
end

also u can use DelegateClass it will do the same trick.

like image 111
Yuri Barbashov Avatar answered Jun 10 '26 08:06

Yuri Barbashov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!