Module: Mongoid::Attributes::InstanceMethods
- Defined in:
- lib/mongoid/attributes.rb
Instance Method Summary collapse
-
#process(attrs = {}) ⇒ Object
Process the provided attributes casting them to their proper values if a field exists for them on the
Document
. -
#read_attribute(name) ⇒ Object
Read a value from the
Document
attributes. -
#remove_attribute(name) ⇒ Object
Remove a value from the
Document
attributes. -
#write_attribute(name, value) ⇒ Object
Write a single attribute to the
Document
attributeHash
. -
#write_attributes(attrs) ⇒ Object
Writes the supplied attributes
Hash
to theDocument
.
Instance Method Details
#process(attrs = {}) ⇒ Object
Process the provided attributes casting them to their proper values if a field exists for them on the Document
. This will be limited to only the attributes provided in the suppied Hash
so that no extra nil values get put into the document’s attributes.
15 16 17 18 19 |
# File 'lib/mongoid/attributes.rb', line 15 def process(attrs = {}) attrs.each_pair do |key, value| send("#{key}=", value) end end |
#read_attribute(name) ⇒ Object
Read a value from the Document
attributes. If the value does not exist it will return nil.
Options:
name: The name of the attribute to get.
Example:
person.read_attribute(:title)
31 32 33 |
# File 'lib/mongoid/attributes.rb', line 31 def read_attribute(name) fields[name].get(@attributes[name]) end |
#remove_attribute(name) ⇒ Object
Remove a value from the Document
attributes. If the value does not exist it will fail gracefully.
Options:
name: The name of the attribute to remove.
Example:
person.remove_attribute(:title)
45 46 47 |
# File 'lib/mongoid/attributes.rb', line 45 def remove_attribute(name) @attributes.delete(name) end |
#write_attribute(name, value) ⇒ Object
Write a single attribute to the Document
attribute Hash
. This will also fire the before and after update callbacks, and perform any necessary typecasting.
Options:
name: The name of the attribute to update. value: The value to set for the attribute.
Example:
person.write_attribute(:title, "Mr.")
This will also cause the observing Document
to notify it’s parent if there is any.
64 65 66 67 68 69 |
# File 'lib/mongoid/attributes.rb', line 64 def write_attribute(name, value) run_callbacks(:before_update) @attributes[name] = fields[name].set(value) run_callbacks(:after_update) notify end |
#write_attributes(attrs) ⇒ Object
Writes the supplied attributes Hash
to the Document
. This will only overwrite existing attributes if they are present in the new Hash
, all others will be preserved.
Options:
attrs: The Hash
of new attributes to set on the Document
Example:
person.write_attributes(:title => "Mr.")
This will also cause the observing Document
to notify it’s parent if there is any.
85 86 87 88 |
# File 'lib/mongoid/attributes.rb', line 85 def write_attributes(attrs) process(attrs) notify end |