Module: MongoODM::Document::Persistence::InstanceMethods

Defined in:
lib/mongo_odm/document/persistence.rb

Instance Method Summary collapse

Instance Method Details

#destroyObject



47
48
49
50
51
52
# File 'lib/mongo_odm/document/persistence.rb', line 47

def destroy
  return false if new_record?
  _run_destroy_callbacks do
    self.class.remove({ :_id => self.id })
  end
end

#idObject



12
13
14
# File 'lib/mongo_odm/document/persistence.rb', line 12

def id
  attributes[:_id]
end

#new_record?Boolean

Returns:



16
17
18
# File 'lib/mongo_odm/document/persistence.rb', line 16

def new_record?
  id.nil?
end

#persisted?Boolean

Returns:



20
21
22
# File 'lib/mongo_odm/document/persistence.rb', line 20

def persisted?
  !new_record?
end

#reloadObject



24
25
26
# File 'lib/mongo_odm/document/persistence.rb', line 24

def reload
  self.load_attributes_or_defaults(self.class.find_one(:_id => id).attributes) unless new_record?
end

#save(options = {}) ⇒ ObjectId

Save a document to its collection.

Parameters:

  • opts (Hash)

    a customizable set of options

Returns:

  • (ObjectId)

    the _id of the saved document.



36
37
38
39
40
# File 'lib/mongo_odm/document/persistence.rb', line 36

def save(options = {})
  _run_save_callbacks do
    write_attribute(:_id, self.class.save(to_mongo, options))
  end
end

#to_dbrefObject



61
62
63
# File 'lib/mongo_odm/document/persistence.rb', line 61

def to_dbref
  BSON::DBRef.new(self.class.collection.name, _id)
end

#to_mongoObject



54
55
56
57
58
59
# File 'lib/mongo_odm/document/persistence.rb', line 54

def to_mongo
  attributes.inject({}) do |attrs, (key, value)|
    attrs[key] = value.to_mongo unless value.nil? # self.class.fields[key].default == value
    attrs
  end
end

#update_attributes(attributes) ⇒ Object



42
43
44
45
# File 'lib/mongo_odm/document/persistence.rb', line 42

def update_attributes(attributes)
  self.attributes = attributes
  save
end