我想在 Ruby 中使用委托,但我不能保证目标对象会响应我将调用的所有方法。我可以用默认行为定义委托吗?
例如
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"
现在,上面的例子会引发:
NoMethodError:
undefined method `age' for #<Student:0xa121212>