Created
February 15, 2013 22:10
-
-
Save deepfryed/4963986 to your computer and use it in GitHub Desktop.
simple convenience wrapper
This file contains 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
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