Class: TimedOpenStruct

Inherits:
OpenStruct show all
Defined in:
lib/australium/timed_open_struct.rb

Direct Known Subclasses

Australium::Player

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ TimedOpenStruct

Returns a new instance of TimedOpenStruct


3
4
5
6
# File 'lib/australium/timed_open_struct.rb', line 3

def initialize(*args)
  super(*args)
  @table_history = Hash.new { |h,k| h[k] = {} }
end

Instance Method Details

#[](name, timestamp = nil) ⇒ Object


8
9
10
11
12
13
14
15
16
17
18
# File 'lib/australium/timed_open_struct.rb', line 8

def [](name, timestamp = nil)
  if timestamp.nil?
    @table[name.to_sym]
  else
    keys = @table_history[name.to_sym].keys.reverse
    key = keys.find(lambda {keys.last}) do |x|
      x <= timestamp
    end
    @table_history[name.to_sym][key]
  end
end

#[]=(name, *args, value) ⇒ Object


20
21
22
23
24
25
26
27
28
# File 'lib/australium/timed_open_struct.rb', line 20

def []=(name, *args, value)
  @table[name.to_sym] = value
  unless args.empty?
    args.each do |timestamp|
      @table_history[name.to_sym].merge!({ timestamp => value })
    end
    @table_history[name.to_sym].replace(@table_history[name.to_sym].sort.to_h)
  end
end

#durations(name) ⇒ Object


30
31
32
33
34
35
36
37
38
39
# File 'lib/australium/timed_open_struct.rb', line 30

def durations(name)
  nil unless @table_history.include?(name.to_sym)

  duration_table = Hash.new(0)
  @table_history[name.to_sym].each_with_index do |(timestamp, value), index|
    duration_table[value] += index == @table_history[name.to_sym].count - 1 ? 0.0 : @table_history[name.to_sym].keys[index + 1] - timestamp
  end

  duration_table
end

#initialize_clone(other) ⇒ Object


41
42
43
44
45
46
47
48
# File 'lib/australium/timed_open_struct.rb', line 41

def initialize_clone(other)
  super(other)
  cloned_history = @table_history.clone
  cloned_history.each_pair do |key, value|
    cloned_history[key] = value.clone
  end
  self.instance_variable_set(:@table_history, cloned_history)
end