Ruby on rails Rails对错误的响应有何反应?

Ruby on rails Rails对错误的响应有何反应?,ruby-on-rails,ruby-on-rails-3.2,Ruby On Rails,Ruby On Rails 3.2,如果rails中不存在方法,我将尝试返回一些内容 我使用的ruby模型如下所示: 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_initia

如果rails中不存在方法,我将尝试返回一些内容

我使用的ruby模型如下所示:

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>
命名错误:
未定义的方法“方法c”#

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

Ruby有一个很好的构造,称为,每当消息发送到一个不处理该方法的对象时,该构造就会被调用。您可以使用它按方法名称动态处理方法:

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

使用define_方法;)
define_方法
在单个实例上运行时是不好的jujuju-它会破坏Ruby全局方法缓存<代码>方法\u缺失是一个更好的工具。这很酷,谢谢!如果你把它作为一个答案发布,我将非常乐意接受它;)