Class: Transformer

Inherits:
Object
  • Object
show all
Extended by:
Attribute
Defined in:
lib/athergin/transformer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Attribute

attribute

Constructor Details

#initialize(name) ⇒ Transformer

Returns a new instance of Transformer.



6
7
8
# File 'lib/athergin/transformer.rb', line 6

def initialize(name)
  @maps, @reduce = [], []
end

Instance Attribute Details

#mapsObject (readonly)

Returns the value of attribute maps.



3
4
5
# File 'lib/athergin/transformer.rb', line 3

def maps
  @maps
end

Instance Method Details

#collection(name = nil) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/athergin/transformer.rb', line 10

def collection(name=nil)
  if name
    if name.is_a? Symbol
      @collection = name
    elsif name.is_a? String
      db,tbl = name.split('/').map(&:to_sym)
      database db
      collection tbl
    end
  else
    @collection
  end
end

#map(hash) ⇒ Object



24
25
26
27
28
# File 'lib/athergin/transformer.rb', line 24

def map(hash)
  raise 'Please specify collection for Transformer map' if hash[:collection].nil?
  raise 'Please specify values for Transformer map' if hash[:values].nil?
  @maps.push hash
end

#mongodb_map_functionsObject



34
35
36
37
38
39
40
41
# File 'lib/athergin/transformer.rb', line 34

def mongodb_map_functions
  erb = File.read('mapreduce/mongodb_map.js.erb')
  maps.map do |map|
    database, collection = map[:collection].split('/')
    function = Erubis::Eruby.new(erb).result keys: map[:keys], values: map[:values]
    [database,collection,function]
  end
end

#mongodb_reduce_functionObject



43
44
45
46
# File 'lib/athergin/transformer.rb', line 43

def mongodb_reduce_function
  erb = File.read('mapreduce/mongodb_reduce.js.erb')
  Erubis::Eruby.new(erb).result defaults: defaults, fields: reduce
end

#run_mapreduceObject



48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/athergin/transformer.rb', line 48

def run_mapreduce
  puts "Dropping collection #{ Platform.database_name(database) }/#{ collection }"
  Platform.database(database.to_s)[collection.to_s].drop

  mongodb_map_functions.each do |map_database,map_collection,mongodb_map_function|
    puts "Loading #{ Platform.database_name(database.to_s) }/#{ collection } from #{ Platform.database_name(map_database) }/#{ map_collection }"
    Platform.database(map_database)[map_collection].map_reduce mongodb_map_function,
                                                               mongodb_reduce_function,
                                                               out: { reduce: collection.to_s, db: Platform.database_name(database.to_s) }
  end

  true
end

#sum(field) ⇒ Object



30
31
32
# File 'lib/athergin/transformer.rb', line 30

def sum(field)
  "+= value.#{ field } ? value.#{ field } : 0"
end