Class: Easymongo::Document
- Inherits:
-
Object
- Object
- Easymongo::Document
- Defined in:
- lib/easymongo/document.rb
Instance Method Summary collapse
-
#attributes ⇒ Object
Get attributes as hash.
-
#attributes=(data) ⇒ Object
Set attributes.
-
#bson_id ⇒ Object
Get bson id.
-
#date ⇒ Object
Creation date.
-
#initialize(doc = {}) ⇒ Document
constructor
Takes a BSON::Document.
-
#method_missing(name, *args, &block) ⇒ Object
Dynamically write value.
Constructor Details
#initialize(doc = {}) ⇒ Document
Takes a BSON::Document
7 8 9 10 11 12 13 14 15 16 17 18 |
# File 'lib/easymongo/document.rb', line 7 def initialize(doc = {}) # Replace _id with id doc['id'] = doc.delete('_id') # Convert all BSON::ObjectId to string doc.each{|k, v| doc[k] = v.to_s if v.is_a?(BSON::ObjectId)} # Write variables # doc.each{|k, v| attr(k, v)} self.attributes = doc end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name, *args, &block) ⇒ Object
Dynamically write value
41 42 43 |
# File 'lib/easymongo/document.rb', line 41 def method_missing(name, *args, &block) return attr(name[0..-2], args[0]) if args.size == 1 and name[-1] == '=' end |
Instance Method Details
#attributes ⇒ Object
Get attributes as hash
21 22 23 |
# File 'lib/easymongo/document.rb', line 21 def attributes Hash[instance_variables.map{|r| [r[1..-1].to_sym, instance_variable_get(r)]}] end |
#attributes=(data) ⇒ Object
Set attributes
26 27 28 |
# File 'lib/easymongo/document.rb', line 26 def attributes=(data) data.each{|k, v| attr(k, v)} end |
#bson_id ⇒ Object
Get bson id
31 32 33 |
# File 'lib/easymongo/document.rb', line 31 def bson_id @bson_id ||= BSON::ObjectId.from_string(@id) end |
#date ⇒ Object
Creation date
36 37 38 |
# File 'lib/easymongo/document.rb', line 36 def date bson_id.generation_time rescue nil end |