Skip to content

Instantly share code, notes, and snippets.

@deepfryed
Created February 15, 2013 22:10
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 deepfryed/4963986 to your computer and use it in GitHub Desktop.
Save deepfryed/4963986 to your computer and use it in GitHub Desktop.
simple convenience wrapper
require 'swift'
module Swift
class Record
def self.first options = {}
filter(Filter.filters(options)).first(Filter.constraints(options))
end
def self.all options = {}
filter(Filter.filters(options)).all(Filter.constraints(options))
end
def self.filter options = {}
Filter.new(self, options)
end
end
class Filter
attr_reader :record, :filter
CONSTRAINTS = [:limit, :offset, :order]
def self.filters hash
hash.reject {|k, v| CONSTRAINTS.include?(k)}
end
def self.constraints hash
hash.select {|k, v| CONSTRAINTS.include?(k)}
end
def initialize record, filter = {}
@record = record
@filter = filter
end
def all options = {}
sql = []
bind = []
where = []
sql = "select * from #{record}"
filter.each do |k, v|
bind << v
where << "#{record.send(k)} %s" % (v.nil? ? "is null" : " = ?")
end
sql.concat(" where #{where.join(' and ')}") unless where.empty?
if order = options[:order]
sql.concat " order by #{order.map {|k, v| '%s %s' % [record.send(k), v]}.join(', ')}"
end
if limit = options[:limit]
sql.concat " limit #{limit}"
end
if offset = options[:offset]
sql.concat " offset #{offset}"
end
record.execute(sql, *bind)
end
def first options = {}
all(options.merge(limit: 1)).first
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment