lib/findable/base.rb in findable-0.1.5 vs lib/findable/base.rb in findable-0.2.0
- old
+ new
@@ -1,46 +1,40 @@
require "findable/associations"
+require "findable/schema"
require "findable/inspection"
module Findable
class Base
include ActiveModel::Model
include ActiveModel::AttributeMethods
include Associations
+ include Schema
include Inspection
- attribute_method_suffix "="
- attribute_method_suffix "?"
-
class << self
- ## field definitions
-
- def define_field(attr)
- unless public_method_defined?(attr)
- define_attribute_methods attr
- define_method(attr) { attributes[attr] }
- column_names << attr.to_sym
- end
+ def arel_table
+ raise NotActiveRecord.new(self)
end
## ActiveRecord like APIs
- delegate :all, to: :query
+ delegate :first, :last, :order, :pluck, to: :all
+ alias_method :take, :first
def primary_key
"id"
end
- def column_names
- @_column_names ||= [:id]
+ def all
+ collection!(query.all)
end
def find(ids)
if records = find_by_ids(ids).presence
- ids.is_a?(Array) ? records : records.first
+ ids.is_a?(Array) ? collection!(records) : records.first
else
- raise RecordNotFound.new(self, id: ids)
+ raise not_found(id: ids)
end
end
def find_by(conditions)
if conditions.is_a?(Hash)
@@ -54,54 +48,44 @@
records.detect {|record|
conditions.all? {|k, v| record.public_send(k) == v }
}
end
else
- all.detect {|record|
- conditions.all? {|k, v| record.public_send(k) == v }
- }
+ all.find_by(conditions.dup)
end
else
find_by_ids(conditions).first
end
end
def find_by!(conditions)
- find_by(conditions.dup) || (raise RecordNotFound.new(self, conditions))
+ find_by(conditions.dup) || (raise not_found(conditions))
end
def where(conditions)
conditions.symbolize_keys!
if id = conditions.delete(:id)
records = find_by_ids(id)
if conditions.empty?
- records
+ collection!(records)
else
- records.select {|record|
+ collection!(records.select {|record|
conditions.all? {|k, v| record.public_send(k) == v }
- }
+ })
end
else
- all.select {|record|
- conditions.all? {|k, v| record.public_send(k) == v }
- }
+ all.where(conditions.dup)
end
end
def create(attrs = {})
record = new(attrs)
record.save
record
end
alias_method :create!, :create
- [:first, :last].each do |m|
- define_method(m) do
- self.all.public_send(m)
- end
- end
-
## Query APIs
delegate :find_by_ids, :insert, to: :query
delegate :count, :ids, :delete_all, to: :query
alias_method :destroy_all, :delete_all
@@ -123,10 +107,18 @@
def query
@_query ||= Query.new(self)
end
private
+ def collection!(records)
+ records.is_a?(Array) ? Collection.new(self, records) : records
+ end
+
+ def not_found(params)
+ RecordNotFound.new(self, params)
+ end
+
def id_from(obj)
obj.is_a?(self) ? obj.id : obj.to_i
end
end
@@ -166,16 +158,8 @@
end
alias_method :destroy, :delete
def attributes
@_attributes ||= ActiveSupport::HashWithIndifferentAccess.new
- end
-
- def attribute=(attr, value)
- attributes[attr.to_sym] = value
- end
-
- def attribute?(attr)
- attributes[attr.to_sym].present?
end
end
end