module Mongocore::Document
Attributes
Public Class Methods
# # # # # # # # # # The class initializer, called when you write Model.new Pass in attributes you want to set: Model.new(:duration => 60) Defaults are filled in automatically.
# File lib/mongocore/document.rb, line 51 def initialize(a = {}) # Store attributes. self.attributes = @_id ? a : self.class.schema.defaults.merge(a) # The _id is a BSON object, create new unless it exists @_id ? @persisted = true : @_id = BSON::ObjectId.new # The errors hash @errors = Hash.new{|h, k| h[k] = []} # The changes hash @changes = Hash.new{|h, k| h[k] = []} end
Public Instance Methods
After
# File lib/mongocore/document.rb, line 354 def after(*args, &block) filters.after[args[0]] << (args[1] || block) end
All
# File lib/mongocore/document.rb, line 289 def all(*args) find(*args).all end
JSON format
# File lib/mongocore/document.rb, line 129 def as_json(o = {}) string_id(attributes(*o[:data])) end
Collect the attributes, pass tags like defined in your model yml
# File lib/mongocore/document.rb, line 114 def attributes(*tags) a = {}; self.class.schema.attributes(tags.map(&:to_s)).each{|k| a[k] = read(k)}; a end
Set the attributes
# File lib/mongocore/document.rb, line 119 def attributes=(a) a.deep_symbolize_keys.each{|k, v| write(k, v)} end
Before
# File lib/mongocore/document.rb, line 359 def before(*args, &block) filters.before[args[0]] << (args[1] || block) end
Changed?
# File lib/mongocore/document.rb, line 124 def changed? @changes.any? end
Count
# File lib/mongocore/document.rb, line 274 def count(*args) find(*args).count end
Delete a document in db
# File lib/mongocore/document.rb, line 84 def delete filter(:delete, false){one.delete} end
Each
# File lib/mongocore/document.rb, line 326 def each(&block) find.each{|r| yield(r)} end
Each with index
# File lib/mongocore/document.rb, line 331 def each_with_index(&block) find.each_with_index{|r, n| yield(r, n)} end
Each with object
# File lib/mongocore/document.rb, line 336 def each_with_object(obj, &block) find.each_with_object(obj){|r, o| yield(r, o)} end
Run filters before and after accessing the db
# File lib/mongocore/document.rb, line 89 def filter(cmd, persisted = true, &block) run(:before, cmd); yield.tap{@persisted = persisted; run(:after, cmd); reset!} end
Find, takes an id or a hash
# File lib/mongocore/document.rb, line 268 def find(*args) mq(self, *args) end
First
# File lib/mongocore/document.rb, line 279 def first(*args) find(*args).first end
Alias for _id but returns string
# File lib/mongocore/document.rb, line 218 def id @_id ? @_id.to_s : nil end
Assign id
# File lib/mongocore/document.rb, line 223 def id=(val) @_id = val.is_a?(BSON::ObjectId) ? val : BSON::ObjectId.from_string(val) end
Insert
# File lib/mongocore/document.rb, line 320 def insert(a = {}, o = {}) r = new(a); r.save(o); r end
Print info about the instance
# File lib/mongocore/document.rb, line 228 def inspect "#<#{self.class} #{attributes.sort.map{|r| %{#{r[0]}: #{r[1].inspect}}}.join(', ')}>" end
Last
# File lib/mongocore/document.rb, line 284 def last(*args) sort(:_id => -1).limit(1).first(*args) end
Limit
# File lib/mongocore/document.rb, line 304 def limit(n = 1) find({}, :limit => n) end
Map
# File lib/mongocore/document.rb, line 341 def map(&block) find.map{|r| yield(r)} end
Dynamically read or write attributes
# File lib/mongocore/document.rb, line 198 def method_missing(name, *args, &block) # Extract name and write mode name =~ /([^=]+)(=)?/ # Write or read if self.class.schema.keys.has_key?(key = $1.to_sym) $2 ? write(key, args.first) : read(key) elsif key =~ /(.+)_changed\?/ # Attributes changed? @changes.has_key?($1.to_sym) elsif key =~ /(.+)_was/ # Attributes was @changes.empty? ? read($1) : @changes[$1.to_sym][0] else # Pass if nothing found super end end
Short cut for setting up a Mongocore::Query
object
# File lib/mongocore/document.rb, line 161 def mq(m, q = {}, o = {}) Mongocore::Query.new(m, q, {:source => self}.merge(o)) end
Short cut for query needing only id
# File lib/mongocore/document.rb, line 166 def one(o = {}) mq(self.class, {:_id => @_id}, o) end
Paginate
# File lib/mongocore/document.rb, line 294 def paginate(*args) find({}).paginate(*args) end
Persist for save and update
# File lib/mongocore/document.rb, line 235 def persist(type, o) # Send :validate => true to validate return false unless valid? if o[:validate] # Create a new query filter(type){one.send((@persisted ? :update : :insert), attributes).ok?} end
Projection
# File lib/mongocore/document.rb, line 314 def projection(o = {}) find({}, :projection => o) end
Get attribute if access
# File lib/mongocore/document.rb, line 176 def read(key) read!(key) if self.class.access.read?((key = key.to_sym)) end
Get attribute
# File lib/mongocore/document.rb, line 254 def read!(key) instance_variable_get("@#{key}") end
Reload the document from db and update attributes
# File lib/mongocore/document.rb, line 94 def reload m = one.first; self.attributes = m.attributes; reset!; self end
Reset internals
# File lib/mongocore/document.rb, line 104 def reset! @changes.clear; @errors.clear end
Available filters are :save, :delete
# File lib/mongocore/document.rb, line 143 def run(filter, key = nil) self.class.filters.run(self, filter, key) end
Save attributes to db
# File lib/mongocore/document.rb, line 74 def save(o = {}) persist(:save, o) end
Saved? Persisted?
# File lib/mongocore/document.rb, line 153 def saved?; !!@persisted; end
Skip
# File lib/mongocore/document.rb, line 309 def skip(n = 0) find({}, :skip => n) end
Sort
# File lib/mongocore/document.rb, line 299 def sort(o = {}) find({}, :sort => o) end
Replace _id with id, takes a hash
# File lib/mongocore/document.rb, line 244 def string_id(a) a.delete(:_id); {:id => id}.merge(a) end
Set the timestamps if enabled
# File lib/mongocore/document.rb, line 99 def timestamps t = Time.now.utc; write(:updated_at, t); write(:created_at, t) if unsaved? end
Unsaved? New record?
# File lib/mongocore/document.rb, line 157 def unsaved?; !@persisted; end
Update document in db
# File lib/mongocore/document.rb, line 79 def update(a = {}, o = {}) self.attributes = a; save(o) end
Valid?
# File lib/mongocore/document.rb, line 138 def valid? @errors.clear; self.class.filters.valid?(self) end
Validate
# File lib/mongocore/document.rb, line 364 def validate(*args, &block) filters.validate << (args[0] || block) end
Set attribute if access
# File lib/mongocore/document.rb, line 181 def write(key, val) return nil unless self.class.access.write?((key = key.to_sym)) # Convert to type as in schema yml v = self.class.schema.set(key, val) if @changes # Record change for dirty attributes r = @changes.has_key?(key) ? @changes[key][0] : read!(key) @changes[key] = [r, v] if r != v end # Write attribute write!(key, v) end
Set attribute
# File lib/mongocore/document.rb, line 249 def write!(key, v) instance_variable_set("@#{key}", v) end