Class: Treat::Workers::Formatters::Serializers::Mongo

Inherits:
Object
  • Object
show all
Defined in:
lib/treat/workers/formatters/serializers/mongo.rb

Overview

Serialization of entities to a Mongo database.

Constant Summary collapse

DefaultOptions =
{
  :recursive => true,
  :stop_at => nil
}

Class Method Summary collapse

Class Method Details

.do_serialize(entity, options) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/treat/workers/formatters/serializers/mongo.rb', line 45

def self.do_serialize(entity, options)

  children = []

  if options[:recursive] && entity.has_children?
    entity.each do |child|
      next if options[:stop_at] && child.class.
      compare_with(options[:stop_at]) < 0
      children << self.do_serialize(child, options)
    end
  end

  entity_token = {
    :id => entity.id,
    :value => entity.value,
    :type => entity.type.to_s,
    :children => children,
    :parent => (entity.has_parent? ? entity.parent.id : nil),
    :features => entity.features
  }

  entity_token

end

.serialize(entity, options = {}) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/treat/workers/formatters/serializers/mongo.rb', line 12

def self.serialize(entity, options = {})

  options = DefaultOptions.merge(options)
  options[:stop_at] = options[:stop_at] ?
  Treat::Entities.const_get(
  options[:stop_at].to_s.capitalize) : nil

  options[:db] ||= Treat.databases.mongo.db
  
  if !options[:db]
    raise Treat::Exception,
    'Must supply the database name in config. ' +
    '(Treat.databases.mongo.db = ...) or pass ' +
    'it as a parameter to #serialize.'
  end

  @@database ||= Mongo::Connection.
  new(Treat.databases.mongo.host).
  db(options[:db])

  supertype =  Treat::Entities.const_get(
  entity.type.to_s.capitalize.intern).superclass.mn.downcase
  supertype = entity.type.to_s if supertype == 'entity'
  supertypes = supertype + 's'
  
  coll = @@database.collection(supertypes)
  entity_token = self.do_serialize(entity, options)
  coll.update({id: entity.id}, entity_token, {upsert: true})
  
  {db: options[:db], collection: supertypes, id: entity.id}
  
end