ruby:委托对象是否响应方法
我希望在Ruby中使用委托,但我不能保证目标对象响应我将调用的所有方法。我可以用默认行为定义委派吗 例如 现在,上述示例将提出:ruby:委托对象是否响应方法,ruby,delegates,activesupport,Ruby,Delegates,Activesupport,我希望在Ruby中使用委托,但我不能保证目标对象响应我将调用的所有方法。我可以用默认行为定义委派吗 例如 现在,上述示例将提出: NoMethodError: undefined method `age' for #<Student:0xa121212> 命名错误: 未定义的方法“年龄”# 不使用委托并像这样手动执行如何 class DummyPresenter def initialize content; @content = content end def na
NoMethodError:
undefined method `age' for #<Student:0xa121212>
命名错误:
未定义的方法“年龄”#
不使用委托并像这样手动执行如何
class DummyPresenter
def initialize content; @content = content end
def name; @content.respond_to?( :name ) ? @content.name : dflt_name end
def age; @content.respond_to?( :age ) ? @content.age :dflt_age end
def to; @content.respond_to?( :to ) ? @content.to :dflt_to end
def dflt_name
nil # or whathever code
end
def dflt_age; nil end
def dflt_to; nil end
end
否则你必须重新编程委托方法,我想
def method_missing(method, *args)
if @content.respond_to? method
@content.send method, *args
else
#your default behaviour (or super)
end
end
您也可以使用DelegateClass,它将执行相同的操作。最后,我使用
define\u方法进行了操作。
:
class DummyPresenter
@@delegated_methods = [:name, :age]
@@delegated_methods.each do |method|
define_method(method) do
return @content.try(method) if @content.respond_to?(method)
nil
end
end
def initialize(content)
@content = content
end
结束我发现将方法委托给原始对象的最简单方法是使用SimpleDelegator(在stdlib中提供)
类演示者“酒吧”
presenter.bam#=>“baz”
从文档中:
SimpleDelegator类提供了委托所有受支持的
方法调用传递给构造函数的对象
嗯,这是我想避免的事情,因为有很多复制的代码只在方法名称上有所不同。@mrzasa这很容易修复,但只需进行一点重构。这是个好主意,但我希望
DummyPresenter
能够响应
添加委派方法,所以define\u method
。如果您已经检查了该方法是否存在,那么使用try有什么意义吗?
class DummyPresenter
@@delegated_methods = [:name, :age]
@@delegated_methods.each do |method|
define_method(method) do
return @content.try(method) if @content.respond_to?(method)
nil
end
end
def initialize(content)
@content = content
end
class Presenter < SimpleDelegator
def initialize model
super model
end
def foo
'bar'
end
end
class Person
def bam
'baz'
end
end
person = Person.new
presenter = Presenter.new Person
presenter.foo # => 'bar'
presenter.bam # => 'baz'