Class: Stamina::Utils::Aggregator

Inherits:
Object
  • Object
show all
Defined in:
lib/stamina-core/stamina/utils/aggregator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize {|_self| ... } ⇒ Aggregator

Returns a new instance of Aggregator.

Yields:

  • (_self)

Yield Parameters:



5
6
7
8
9
# File 'lib/stamina-core/stamina/utils/aggregator.rb', line 5

def initialize
  @functions = {}
  @default   = nil
  yield(self) if block_given?
end

Instance Attribute Details

#functionsObject (readonly)

Returns the value of attribute functions.



10
11
12
# File 'lib/stamina-core/stamina/utils/aggregator.rb', line 10

def functions
  @functions
end

Instance Method Details

#aggregate(enum) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/stamina-core/stamina/utils/aggregator.rb', line 35

def aggregate(enum)
  memo = nil
  enum.each do |tuple|
    memo = memo ? merge(memo, tuple) : tuple
  end
  memo
end

#default(function = nil, &bl) ⇒ Object



16
17
18
# File 'lib/stamina-core/stamina/utils/aggregator.rb', line 16

def default(function = nil, &bl)
  @default = function || bl
end

#ignore(key) ⇒ Object



20
21
22
# File 'lib/stamina-core/stamina/utils/aggregator.rb', line 20

def ignore(key)
  register(key, lambda{|v1,v2| throw :ignore })
end

#merge(t1, t2) ⇒ Object



24
25
26
27
28
29
30
31
32
33
# File 'lib/stamina-core/stamina/utils/aggregator.rb', line 24

def merge(t1, t2)
  tuple = {}
  t1.keys.each do |k|
    next unless fn = functions[k] || @default
    catch :ignore do
      tuple[k] = fn.call(t1[k], t2[k])
    end
  end
  tuple
end

#register(key, function = nil, &bl) ⇒ Object



12
13
14
# File 'lib/stamina-core/stamina/utils/aggregator.rb', line 12

def register(key, function = nil, &bl)
  functions[key] = function || bl
end