Sha256: 8130ceb4230094f5692f688a63f77ba7eacb775260f3b9d369c36afbfb1b9177
Contents?: true
Size: 1.08 KB
Versions: 1
Compression:
Stored size: 1.08 KB
Contents
# The mongodb document module Easymongo class Document # Takes a BSON::Document 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 # Get attributes as hash def attributes Hash[instance_variables.map{|r| [r[1..-1].to_sym, instance_variable_get(r)]}] end # Set attributes def attributes=(data) data.each{|k, v| attr(k, v)} end # Get bson id def bson_id @bson_id ||= BSON::ObjectId.from_string(@id) end # Creation date def date bson_id.generation_time rescue nil end # Dynamically write value def method_missing(name, *args, &block) return attr(name[0..-2], args.first) if args.size == 1 and name[-1] == '=' end private # Create accessor def attr(k, v) singleton_class.class_eval { attr_accessor k }; send("#{k}=", v) end end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
easymongo-0.0.6 | lib/easymongo/document.rb |