Skip to content

Instantly share code, notes, and snippets.

@blairanderson
Forked from pjb3/query.rb
Last active December 15, 2015 04:59
Show Gist options
  • Save blairanderson/5205620 to your computer and use it in GitHub Desktop.
Save blairanderson/5205620 to your computer and use it in GitHub Desktop.
Create a ruby hash by chaining methods.
class Query
def initialize
@hash = {}
end
def method_missing(name, *args)
value = args.length > 0 ? args.first : true
@hash.merge!(name => value)
self
end
def to_hash
@hash.dup
end
end
puts Query.new.female.zip("90210").city('Los Angelos').age(21).state("CA").to_hash.inspect
# => {:female=>true, :zip=>"90210", :city=>"Los Angelos", :age=>21, :state=>"CA"}
puts Query.new.for_sale.in_stock.inventory(30).current_price(3499).made_in("USA").category_code("000-001").category("product").sub_category("power cord").sub_category_code("000-009").to_hash.inspect
# => {:for_sale=>true, :in_stock=>true, :inventory=>30, :current_price=>3499, :made_in=>"USA", :category_code=>"000-001", :category=>"product", :sub_category=>"power cord", :sub_category_code=>"000-009"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment