module Jsonoid::Document
Public Class Methods
included(base)
click to toggle source
# File lib/jsonoid/document.rb, line 6 def included(base) base.extend(ClassMethods) end
new(data={})
click to toggle source
# File lib/jsonoid/document.rb, line 11 def initialize(data={}) @_data = {} update_attributes(data) end
Public Instance Methods
destroy()
click to toggle source
# File lib/jsonoid/document.rb, line 77 def destroy errors.clear! trigger(:before_destroy) self.class.collection.delete(id) true rescue NotFound => e errors.add(:id, e.message) false end
errors()
click to toggle source
# File lib/jsonoid/document.rb, line 58 def errors @errors ||= Errors.new end
id()
click to toggle source
# File lib/jsonoid/document.rb, line 16 def id @_data[:_id] end
new_record?()
click to toggle source
# File lib/jsonoid/document.rb, line 20 def new_record? id.new? end
save()
click to toggle source
# File lib/jsonoid/document.rb, line 62 def save errors.clear! trigger(:validate) return false if errors.any? trigger(:before_save) self.class.collection.write(id, @_data.to_json) true rescue NotPersisted => e errors.add(:id, e.message) false end
to_hash()
click to toggle source
# File lib/jsonoid/document.rb, line 89 def to_hash @_data.to_hash end
to_json(*args)
click to toggle source
# File lib/jsonoid/document.rb, line 97 def to_json(*args) @_data.to_json(*args) end
to_s()
click to toggle source
# File lib/jsonoid/document.rb, line 93 def to_s @_data.to_s end
trigger(type)
click to toggle source
# File lib/jsonoid/callbacks.rb, line 3 def trigger(type) raise ArgumentError, 'Type must be a Symbol' unless type.is_a? Symbol self.class.send("_#{type}_callbacks".to_sym).each do |callback| send(callback) end end
update_attributes(data)
click to toggle source
# File lib/jsonoid/document.rb, line 24 def update_attributes(data) raise ArgumentError, 'Data must be a valid Hash' unless data.is_a? Hash data.keys.each do |k| data[k.to_sym] = data.delete(k) end self.class.fields.each do |(name, type, default)| value = data.delete(name) if value.nil? @_data[name] = default ? default.dup : nil elsif type < Document if value.is_a?(Array) and default.is_a?(Array) @_data[name] = value.map do |v| v.is_a?(Hash) ? type.new(v) : v end elsif value.is_a?(Hash) @_data[name] = type.new(value) else @_data[name] = value end else @_data[name] = type.respond_to?(:parse) ? type.parse(value) : value end end if @_data[:id].nil? @_data[:_id] = ObjectId.parse(data[:_id]) else save end end