lib/supermodel/base.rb in supermodel-0.1.2 vs lib/supermodel/base.rb in supermodel-0.1.3

- old
+ new

@@ -3,10 +3,16 @@ class_inheritable_array :known_attributes self.known_attributes = [] class << self attr_accessor_with_default(:primary_key, 'id') #:nodoc: + + def collection(&block) + @collection ||= Class.new(Array) + @collection.class_eval(&block) if block_given? + @collection + end def attributes(*attributes) self.known_attributes += attributes.map(&:to_s) end @@ -17,12 +23,17 @@ def find_by_attribute(name, value) #:nodoc: item = records.values.find {|r| r.send(name) == value } item && item.dup end + def find_all_by_attribute(name, value) #:nodoc: + items = records.values.select {|r| r.send(name) == value } + collection.new(items) + end + def raw_find(id) #:nodoc: - records[id] || raise(UnknownRecord) + records[id] || raise(UnknownRecord, "Couldn't find #{self.name} with ID=#{id}") end # Find record by ID, or raise. def find(id) item = raw_find(id) @@ -38,16 +49,20 @@ def last item = records.values[-1] item && item.dup end + def exists?(id) + records.has_key?(id) + end + def count records.length end def all - records.values.dup + collection.new(records.values) end def update(id, atts) find(id).update_attributes(atts) end @@ -71,22 +86,28 @@ # Create a new record. # Example: # create(:name => "foo", :id => 1) def create(atts = {}) rec = self.new(atts) - rec.save! && rec + rec.save && rec end + def create!(*args) + create(*args) || raise(InvalidRecord) + end + def method_missing(method_symbol, *args) #:nodoc: method_name = method_symbol.to_s if method_name =~ /^find_by_(\w+)!/ send("find_by_#{$1}", *args) || raise(UnknownRecord) elsif method_name =~ /^find_by_(\w+)/ find_by_attribute($1, args.first) elsif method_name =~ /^find_or_create_by_(\w+)/ send("find_by_#{$1}", *args) || create($1 => args.first) + elsif method_name =~ /^find_all_by_(\w+)/ + find_all_by_attribute($1, args.first) else super end end end @@ -99,10 +120,11 @@ end def initialize(attributes = {}) @new_record = true @attributes = {}.with_indifferent_access + @changed_attributes = {} load(attributes) end def clone cloned = attributes.reject {|k,v| k == self.class.primary_key } @@ -173,10 +195,14 @@ def update_attributes(attributes) load(attributes) && save end + def update_attributes!(attributes) + update_attributes(attributes) || raise(InvalidRecord) + end + def has_attribute?(name) @attributes.has_key?(name) end alias_method :respond_to_without_attributes?, :respond_to? @@ -257,12 +283,13 @@ end end end class Base - extend ActiveModel::Naming + extend ActiveModel::Naming include ActiveModel::Conversion include ActiveModel::Serializers::JSON include ActiveModel::Serializers::Xml include Dirty, Observing, Callbacks, Validations + include Association::Model end end \ No newline at end of file