class Easymongo::Document

Public Class Methods

new(doc = {}) click to toggle source

Takes a BSON::Document

# 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

Public Instance Methods

attributes() click to toggle source

Get attributes as hash

# 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) click to toggle source

Set attributes

# File lib/easymongo/document.rb, line 26
def attributes=(data)
  data.each{|k, v| attr(k, v)}
end
bson_id() click to toggle source

Get bson id

# File lib/easymongo/document.rb, line 31
def bson_id
  @bson_id ||= BSON::ObjectId.from_string(@id)
end
date() click to toggle source

Creation date

# File lib/easymongo/document.rb, line 36
def date
  bson_id.generation_time rescue nil
end
method_missing(name, *args, &block) click to toggle source

Dynamically write value

# 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

Private Instance Methods

attr(k, v) click to toggle source

Create accessor

# File lib/easymongo/document.rb, line 48
def attr(k, v)
  singleton_class.class_eval { attr_accessor k }; send("#{k}=", v)
end