lib/supermodel/base.rb in supermodel-0.0.6 vs lib/supermodel/base.rb in supermodel-0.0.8
- old
+ new
@@ -1,26 +1,28 @@
module SuperModel
class Base
include ActiveModel::Dirty
-
+ class_inheritable_array :known_attributes
+ self.known_attributes = []
+
class << self
attr_accessor_with_default(:primary_key, 'id') #:nodoc:
-
+
def attributes(*attributes)
- @known_attributes = attributes.map(&:to_s)
+ self.known_attributes += attributes.map(&:to_s)
end
- def known_attributes
- @known_attributes ||= []
- end
-
def records
@records ||= []
end
+ def find_by_attribute(name, value) #:nodoc:
+ records.find {|r| r.send(name) == value }
+ end
+
def raw_find(id) #:nodoc:
- records.find {|r| r.id == id } || raise(UnknownRecord)
+ find_by_attribute(:id, id) || raise(UnknownRecord)
end
# Find record by ID, or raise.
def find(id)
item = raw_find(id)
@@ -44,12 +46,12 @@
def all
records.dup
end
- def update(id, data)
- find(id).update(data)
+ def update(id, atts)
+ find(id).update_attributes(atts)
end
def destroy(id)
find(id).destroy
end
@@ -72,14 +74,10 @@
def create(atts = {})
rec = self.new(atts)
rec.save && rec
end
- def find_by_attribute(name, value) #:nodoc:
- records.find {|r| r.name == value }
- 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)
@@ -92,16 +90,18 @@
end
end
end
attr_accessor :attributes
+ attr_writer :new_record
def known_attributes
self.class.known_attributes + self.attributes.keys.map(&:to_s)
end
def initialize(attributes = {})
+ @new_record = true
@attributes = {}.with_indifferent_access
load(attributes)
end
def clone
@@ -112,11 +112,11 @@
end
self.class.new(cloned)
end
def new?
- id.nil?
+ @new_record || false
end
alias :new_record? :new?
# Gets the <tt>\id</tt> attribute of the item.
def id
@@ -141,11 +141,12 @@
id.hash
end
def dup
self.class.new.tap do |base|
- base.attributes = @attributes.dup
+ base.attributes = attributes
+ base.new_record = new_record?
end
end
def save
new? ? create : update
@@ -191,12 +192,16 @@
else
super
end
end
- def destroy
+ def raw_destroy
self.class.records.delete(self)
+ end
+
+ def destroy
+ raw_destroy
self
end
protected
def read_attribute(name)
@@ -209,19 +214,30 @@
def generate_id
object_id
end
+ def raw_create
+ self.class.records << self.dup
+ end
+
def create
self.id ||= generate_id
- self.class.records << self.dup
+ self.new_record = false
+ raw_create
save_previous_changes
+ self.id
end
- def update
+ def raw_update
item = self.class.raw_find(id)
item.load(attributes)
+ end
+
+ def update
+ raw_update
save_previous_changes
+ true
end
def save_previous_changes
@previously_changed = changes
changed_attributes.clear
\ No newline at end of file