0

如果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>

我知道这听起来很疯狂,但是如果该方法不存在,我该怎么做才能返回一些东西?

4

1 回答 1

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
于 2013-09-06T17:39:58.243 回答