如果rails中不存在某个方法,我正在尝试返回一些内容。
我看起来像这样的红宝石模型:
class myModel
attr_accessible :attr_a, :attr_b, #name of attributes `attr_c` and `attr_d`
:attr_c, :attr_d #are equal to `method_c` and `method_d` names
#init some values
after_initialize :default_values
def default_values
self.is_active ||= true
self.attr_a ||= 'None'
self.attr_b ||= 1
if !self.respond_to?("method_c")
#return something if the method is called
self.method_c = 'None' #not working
end
if !self.respond_to?("method_d")
#return something if the method is called
self.method_d = 'None' #not working
end
end
#more methods
end
但是我的规范测试中出现错误:
NoMethodError:
undefined method `method_c' for #<Object:0xbb9e53c>
我知道这听起来很疯狂但是,如果方法不存在,我该怎么做才能返回?
答案 0 :(得分:2)
Ruby有一个名为#method_missing的优秀构造,只要将消息发送到不处理该方法的对象,就会调用它。您可以使用它通过方法名称动态处理方法:
class MyModel
attr_accessible :attr_a, :attr_b, #name of attributes `attr_c` and `attr_d`
:attr_c, :attr_d #are equal to `method_c` and `method_d` names
#init some values
after_initialize :default_values
def default_values
self.is_active ||= true
self.attr_a ||= 'None'
self.attr_b ||= 1
end
def method_missing(method, *args)
case method
when :method_c
attr_c = "None" # Assigns to attr_c and returns "None"
when :method_d
attr_d = "None" # Assigns to attr_d and returns "None"
else
super # If it wasn't handled, then just pass it on, which will result in an exception.
end
end
end