Module: MongoPersist

Included in:
Customer, Order, OrderProduct, Product
Defined in:
lib/mongo_persist/base.rb

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

NIL_OBJ =
99999

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#mongo_idObject

Returns the value of attribute mongo_id.



24
25
26
# File 'lib/mongo_persist/base.rb', line 24

def mongo_id
  @mongo_id
end

Class Method Details

.included(mod) ⇒ Object



88
89
90
91
92
# File 'lib/mongo_persist/base.rb', line 88

def self.included(mod)
  super(mod)
  mod.send(:include,FromHash)
  mod.send(:extend,ClassMethods)
end

Instance Method Details

#can_mongo_convert?Boolean

Returns:

  • (Boolean)


65
66
67
# File 'lib/mongo_persist/base.rb', line 65

def can_mongo_convert?
  true
end

#from_mongo_hash(h) ⇒ Object



59
60
61
62
# File 'lib/mongo_persist/base.rb', line 59

def from_mongo_hash(h)
  h = h.map_value { |v| v.safe_to_mongo_object }
  from_hash(h)
end

#mongo_addl_attributesObject



29
30
31
# File 'lib/mongo_persist/base.rb', line 29

def mongo_addl_attributes
  []
end

#mongo_attributesObject

can be overriden by class. If not, assumes that all instance variables should be saved.



26
27
28
# File 'lib/mongo_persist/base.rb', line 26

def mongo_attributes
  (instance_variables.map { |x| x[1..-1] } - ['mongo','mongo_id']).select { |x| respond_to?(x) }
end

#mongo_child_attributesObject



32
33
34
# File 'lib/mongo_persist/base.rb', line 32

def mongo_child_attributes
  (mongo_attributes - self.class.mongo_reference_attributes + mongo_addl_attributes).uniq
end

#new_hashx(attr, h, obj) ⇒ Object



38
39
40
41
42
43
44
45
46
# File 'lib/mongo_persist/base.rb', line 38

def new_hashx(attr,h,obj)
  if obj.can_mongo_convert?
    h.merge(attr => obj.to_mongo_hash) 
  else
    h
  end
rescue
  return h
end

#to_mongo_hashObject



47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/mongo_persist/base.rb', line 47

def to_mongo_hash
  res = mongo_child_attributes.inject({}) do |h,attr| 
    obj = send(attr)
    #raise "#{attr} is nil" unless obj
    new_hashx(attr,h,obj)
  end.merge("_mongo_class" => self.class.to_s)
  klass.mongo_reference_attributes.each do |attr|
    val = send(attr)
    res[attr] = val.to_mongo_ref_hash if val
  end
  res
end

#to_mongo_ref_hashObject



35
36
37
# File 'lib/mongo_persist/base.rb', line 35

def to_mongo_ref_hash
  {'_mongo_class' => klass.to_s, '_id' => mongo_id}
end