我有一个类,我正在使用通过方法链构建复杂对象。我是新来的红宝石,所以我必须在这里丢失一些明显的东西。我期望返回一个哈希看起来像这样:{"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
非常感谢您为我的代码提供的任何灯光。
在方法的末尾没有明确地返回某些东西,这更具有地道性。例如,在'equals'方法的最后一行,只需写'self'而不是'return self'。 – yihangho
这应该不会有所作为。 –
它不应该。我只是说它比较习惯,不会解决问题。 – yihangho