I have a class I'm using build complex objects via method chaining. I'm new to ruby so I must be missing something obvious here. I expect a hash to be returned that looks like this: {"must"=>[{:match=>{"status_type" : "good"}}, {:match=>{"product_age" : "old"}}]}
But all I get is this: {"must"=>[{:match=>{}}]}
I invoke the following code for the above attempts:
builder = QueryBuilder.new
built = builder.must("status_type").equals("good").must("product_age").equals("old")
built.serialize_this
Here is my class. I'd appreciate any help as I'm pretty new to 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
Thanks a ton in advance for any light you can shed on my code.