Skip to content

Commit

Permalink
Using allocate to create new instance from database. Separated initia…
Browse files Browse the repository at this point in the history
…lize and initialize_from_database instead of having two parameters for initialize. Should make overriding initialize/etc easier.
  • Loading branch information
jnunemaker committed Aug 29, 2010
1 parent 67583fd commit abf2168
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 18 deletions.
16 changes: 10 additions & 6 deletions lib/mongo_mapper/plugins/dirty.rb
Expand Up @@ -39,25 +39,29 @@ def changes
changed.inject({}) { |h, key| h[key] = key_change(key); h }
end

def initialize(*args)
super
changed_keys.clear if args.first.blank? || !new?
def initialize(*)
# never register initial id assignment as a change
super.tap { changed_keys.delete('_id') }
end

def save(*args)
def initialize_from_database(*)
super.tap { changed_keys.clear }
end

def save(*)
if status = super
changed_keys.clear
end
status
end

def save!(*args)
def save!(*)
status = super
changed_keys.clear
status
end

def reload(*args)
def reload(*)
document = super
changed_keys.clear
document
Expand Down
23 changes: 11 additions & 12 deletions lib/mongo_mapper/plugins/keys.rb
Expand Up @@ -63,11 +63,10 @@ def from_mongo(value)
def load(attrs)
return nil if attrs.nil?
begin
klass = attrs['_type'].present? ? attrs['_type'].constantize : self
klass.new(attrs, true)
attrs['_type'].present? ? attrs['_type'].constantize : self
rescue NameError
new(attrs, true)
end
self
end.allocate.initialize_from_database(attrs)
end

private
Expand Down Expand Up @@ -160,16 +159,16 @@ def create_validations_for(key)
end

module InstanceMethods
def initialize(attrs={}, from_database=false)
def initialize(attrs={})
default_id_value(attrs)
@_new = true
assign(attrs)
end

if from_database
@_new = false
load_from_database(attrs)
else
@_new = true
assign(attrs)
end
def initialize_from_database(attrs={})
@_new = false
load_from_database(attrs)
self
end

def persisted?
Expand Down

0 comments on commit abf2168

Please sign in to comment.