Module: MongoMapper::EmbeddedDocument::InstanceMethods

Defined in:
lib/mongomapper/embedded_document.rb

Instance Method Summary collapse

Instance Method Details

#==(other) ⇒ Object



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

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

#[](name) ⇒ Object



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

def [](name)
  read_attribute(name)
end

#[]=(name, value) ⇒ Object



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

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

#attributesObject



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/mongomapper/embedded_document.rb', line 187

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



174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/mongomapper/embedded_document.rb', line 174

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



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

def id
  read_attribute(:_id)
end

#id=(value) ⇒ Object



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

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
169
170
171
172
# 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
    
    if respond_to?(:_type=) && self['_type'].blank?
      self._type = self.class.name
    end
  end

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

#inspectObject



230
231
232
233
234
235
# File 'lib/mongomapper/embedded_document.rb', line 230

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:



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

def using_custom_id?
  !!@using_custom_id
end