Skip to content

Instantly share code, notes, and snippets.

@iHiD
Created October 24, 2013 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iHiD/7139437 to your computer and use it in GitHub Desktop.
Save iHiD/7139437 to your computer and use it in GitHub Desktop.
Rebuilding Inquisitio
class Inquisitio
attr_reader :criteria, :limit, :order
def initialize
@criteria = []
@limit = 10
yield(self) if block_given?
end
def self.method_missing(name, *args)
new.send(name, *args)
end
def where(criteria)
clone { |i| i.criteria << criteria }
end
def limit(limit)
clone { |i| i.limit = limit }
end
def order(order)
clone { |i| i.order = order }
end
protected
attr_writer :criteria, :limit, :order
def clone
Inquisitio.new do |i|
i.instance_variable_set(:@criteria, @criteria)
i.instance_variable_set(:@limit, @limit)
i.instance_variable_set(:@order, @order)
yield i
end
end
end
thing = Inquisitio.where(x: true).limit(5).order('foobar desc')
thing = thing.where(y: false)
p thing
class Inquisitio
ArrayAttrs = {criteria: :where}
ObjectAttrs = [:limit, :order]
attr_reader *ArrayAttrs.keys
attr_reader *ObjectAttrs
def initialize
@criteria = []
@limit = 10
yield(self) if block_given?
end
def self.method_missing(name, *args)
new.send(name, *args)
end
ArrayAttrs.each do |attr, method|
define_method method do |val|
clone { |i| i.send(attr) << val }
end
end
ObjectAttrs.each do |attr|
define_method attr do |val|
clone { |i| i.send("#{attr}=", val) }
end
end
protected
attr_writer *ArrayAttrs.keys
attr_writer *ObjectAttrs
def clone
Inquisitio.new do |i|
(ObjectAttrs + ArrayAttrs.keys).each do |attr|
i.instance_variable_set("@#{attr}", instance_variable_get("@#{attr}"))
end
yield i
end
end
end
thing = Inquisitio.where(x: true).limit(5).order("foobar desc")
thing = thing.where(y: false)
p thing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment