Module: MongoMapper::EmbeddedDocument::InstanceMethods

Defined in:
lib/mongomapper/embedded_document.rb

Instance Method Summary collapse

Instance Method Details

#==(other) ⇒ Object



209
210
211
# File 'lib/mongomapper/embedded_document.rb', line 209

def ==(other)
  other.is_a?(self.class) && id == other.id
end

#[](name) ⇒ Object



200
201
202
# File 'lib/mongomapper/embedded_document.rb', line 200

def [](name)
  read_attribute(name)
end

#[]=(name, value) ⇒ Object



204
205
206
207
# File 'lib/mongomapper/embedded_document.rb', line 204

def []=(name, value)
  ensure_key_exists(name)
  write_attribute(name, value)
end

#attributesObject



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/mongomapper/embedded_document.rb', line 183

def attributes
  attrs = HashWithIndifferentAccess.new
  self.class.keys.each_pair do |name, key|
    value = 
      if key.native?
        read_attribute(key.name)
      else
        if embedded_document = read_attribute(key.name)
          embedded_document.attributes
        end
      end
    
    attrs[name] = value unless value.nil?
  end
  attrs.merge!(embedded_association_attributes)
end

#attributes=(attrs) ⇒ Object



170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/mongomapper/embedded_document.rb', line 170

def attributes=(attrs)
  return if attrs.blank?
  attrs.each_pair do |name, value|
    writer_method = "#{name}="
    
    if respond_to?(writer_method)
      self.send(writer_method, value)
    else
      self[name.to_s] = value
    end
  end
end

#idObject



213
214
215
# File 'lib/mongomapper/embedded_document.rb', line 213

def id
  read_attribute(:_id)
end

#id=(value) ⇒ Object



217
218
219
220
# File 'lib/mongomapper/embedded_document.rb', line 217

def id=(value)
  @using_custom_id = true
  write_attribute :_id, value
end

#initialize(attrs = {}) ⇒ Object



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/mongomapper/embedded_document.rb', line 154

def initialize(attrs={})
  unless attrs.nil?
    self.class.associations.each_pair do |name, association|
      if collection = attrs.delete(name)
        send("#{association.name}=", collection)
      end
    end

    self.attributes = attrs
  end

  if self.class.embeddable? && read_attribute(:_id).blank?
    write_attribute :_id, XGen::Mongo::Driver::ObjectID.new.to_s
  end
end

#inspectObject



226
227
228
229
230
231
# File 'lib/mongomapper/embedded_document.rb', line 226

def inspect
  attributes_as_nice_string = self.class.keys.keys.collect do |name|
    "#{name}: #{read_attribute(name)}"
  end.join(", ")
  "#<#{self.class} #{attributes_as_nice_string}>"
end

#using_custom_id?Boolean

Returns:



222
223
224
# File 'lib/mongomapper/embedded_document.rb', line 222

def using_custom_id?
  !!@using_custom_id
end