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>
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.
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