Rails Method_missing从散列中返回值

时间:2012-04-25 11:10:22

标签: ruby-on-rails ruby method-missing

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

一个例子就像

 @month_id.number_of_white_envelopes_made

在哈希

 @data_hash[number_of_white_envelopes_made] => 1

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

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

编辑:好吧,所以我在偷偷摸摸,这就是我想出来的

 def method_missing(method)
   if @data_hash.has_key? method.to_sym
     return @data_hash[method]
   else
     super
   end
 end

有更好的方法吗?

2 个答案:

答案 0 :(得分:6)

如下:

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

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

def respond_to?(method_sym, include_private = false)
  if @data_hash.include? method_sym
    true
  else
    super
  end
end

答案 1 :(得分:1)

最短的是

class Hash
  def method_missing(sym,*)
    fetch(sym){fetch(sym.to_s){super}}
  end
end

首先尝试hash[:key]然后hash["key"]

相关问题