lib/findable/base.rb in findable-0.2.1 vs lib/findable/base.rb in findable-0.2.2

- old
+ new

@@ -3,11 +3,10 @@ require "findable/inspection" module Findable class Base include ActiveModel::Model - include ActiveModel::AttributeMethods include Associations include Schema include Inspection class << self @@ -37,12 +36,18 @@ end def find_by(conditions) if conditions.is_a?(Hash) conditions.symbolize_keys! - if id = conditions.delete(:id) - records = find_by_ids(id) + if index = conditions.keys.detect {|key| key.in?(indexes) } + value = conditions.delete(index) + if index == :id + records = find_by_ids(value) + else + records = find_by_index(index, value) + end + case when records.empty? then nil when conditions.empty? then records.first else records.detect {|record| @@ -61,12 +66,18 @@ 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 index = conditions.keys.detect {|key| key.in?(indexes) } + value = conditions.delete(index) + if index == :id + records = find_by_ids(value) + else + records = find_by_index(index, value) + end + if conditions.empty? collection!(records) else collection!(records.select {|record| conditions.all? {|k, v| record.public_send(k) == v } @@ -82,26 +93,27 @@ record.save record end alias_method :create!, :create + ## Extension + + def ordered_find(*_ids) + _ids.flatten! + find(_ids).ordered_find(_ids) + end + ## Query APIs - delegate :find_by_ids, :insert, to: :query - delegate :count, :ids, :delete_all, to: :query + delegate :find_by_ids, :find_by_index, :insert, to: :query + delegate :count, :ids, :delete, :delete_all, to: :query alias_method :destroy_all, :delete_all def exists?(obj) if _id = id_from(obj) query.exists?(_id) else false - end - end - - def delete(obj) - if _id = id_from(obj) - query.delete(_id) end end def query @_query ||= Query.new(self)