Rails Method_missing从散列中返回值

The*_*end 0 ruby ruby-on-rails method-missing

我正在尝试编写一个method_missing方法,这样当我运行一个方法时,它必须点击哈希并查看键,如果它找到匹配以返回值.并继续.哈希是从我写的sql查询填充的,所以值永远不会是常量.

一个例子就像

 @month_id.number_of_white_envelopes_made
Run Code Online (Sandbox Code Playgroud)

在哈希

 @data_hash[number_of_white_envelopes_made] => 1
Run Code Online (Sandbox Code Playgroud)

所以@month_id将返回1.我以前从未使用过它,没有多少材料使用哈希作为回落方法丢失

编辑:抱歉,我忘了说,如果它没有在哈希中找到方法,那么它可以继续向下没有方法错误

编辑:好吧,所以我被黑客攻击,这就是我想出的

 def method_missing(method)
   if @data_hash.has_key? method.to_sym
     return @data_hash[method]
   else
     super
   end
 end
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?

Alb*_*ini 6

怎么样的:

def method_missing(method_sym, *arguments, &block)
  if @data_hash.include? method_sym
    @data_hash[method_sym]
  else
    super
  end
end
Run Code Online (Sandbox Code Playgroud)

并始终记得添加相应的respond_to?对你的对象:

def respond_to?(method_sym, include_private = false)
  if @data_hash.include? method_sym
    true
  else
    super
  end
end
Run Code Online (Sandbox Code Playgroud)