2015-07-22 54 views
0

我有一个类,我正在使用通过方法链构建复杂对象。我是新来的红宝石,所以我必须在这里丢失一些明显的东西。我期望返回一个哈希看起来像这样:{"must"=>[{:match=>{"status_type" : "good"}}, {:match=>{"product_age" : "old"}}]}实例变量似乎没有在ruby方法链接中填充

但我得到的是这样的:{"must"=>[{:match=>{}}]}

我援引上述尝试下面的代码:

builder = QueryBuilder.new 
built = builder.must("status_type").equals("good").must("product_age").equals("old") 
built.serialize_this 

这里是我的课。我很感激任何帮助,因为我对Ruby很新。

class QueryBuilder 
    attr_accessor :query_hash, :context, :condition_hash 

    def initialize 
     @query_hash = {} 
     @condition_hash = {} 
    end 

    def serialize_this 
     return @query_hash 
    end 

    def must(search_field) 
     @context = "must" 
     @condition_hash[search_field] = "temp" 
     return self 
    end 

    def should(search_field) 
     @context = "should" 
     @condition_hash[search_field] = "temp" 
     return self 
    end 

    def equals(value_field) 
     search_field = @condition_hash.keys[0].to_s 
     @condition_hash[search_field] = value_field 
     match_hash = {} 
     match_hash[:match] = @condition_hash 
     an_array =[] 
     an_array << match_hash 
     @query_hash[@context] = an_array 
     @condition_hash.clear 
    return self 
    end 
end 

非常感谢您为我的代码提供的任何灯光。

+0

在方法的末尾没有明确地返回某些东西,这更具有地道性。例如,在'equals'方法的最后一行,只需写'self'而不是'return self'。 – yihangho

+0

这应该不会有所作为。 –

+0

它不应该。我只是说它比较习惯,不会解决问题。 – yihangho

回答

1

当你这样做:

match_hash [:匹配] = @condition_hash

你不把哈希值的副本存在,你把一个参考的哈希值。这是你后来清楚的一样的散列。

Is Ruby pass by reference or by value?

+0

太棒了!那确实解决了空的散列问题,但是它错过了status_type =>好。它只显示第二个散列,即:'{“must”=> [{:match => {“product_age”=>“old”}}]}' –

+0

当然,每次实例化一个新数组,对它的价值。旧阵列丢失。 – wired9

+0

明白了。我看到我们必须这样做:'(@query_hash [@context] || = [])<< match_hash ' –