Skip to content

Instantly share code, notes, and snippets.

@michaelminter
Created February 17, 2021 21:04
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 michaelminter/c1182602a70442b83010322c5de71a20 to your computer and use it in GitHub Desktop.
Save michaelminter/c1182602a70442b83010322c5de71a20 to your computer and use it in GitHub Desktop.
class BaseQuery
attribute_accessor :object, :query
def initialize
@object = Null
@query = [@object]
end
def execute
@query.map.with_index { |q, i| i == 0 ? q : merge(q) }.join(send '.') # wtf
end
private
def self.queries(*names)
names.each do |name|
define_method name do |*args|
@query << send("_#{name}", args)
self
end
end
end
end
class NullQuery < BaseQuery
queries :this, :that, :void
private
def _this(arg)
joins(:something).where(something: { id: arg })
end
def _that
where(thing: 1 || 2)
end
def _void
where(:vampire > :werewolf)
end
end
NullQuery.new.this(37).that.execute
#=> SELECT * FROM nulls INNER JOIN somethings WHERE somethings.id = 37 AND (nulls.thing = 1 OR nulls.thing = 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment