Created
October 24, 2013 15:36
-
-
Save iHiD/7139437 to your computer and use it in GitHub Desktop.
Rebuilding Inquisitio
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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