Class: Dboard::Collector

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/collector.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeCollector

Returns a new instance of Collector.



22
23
24
25
# File 'lib/collector.rb', line 22

def initialize
  @sources = {}
  @after_update_callback = lambda {}
end

Instance Attribute Details

#sourcesObject (readonly)

Returns the value of attribute sources.



8
9
10
# File 'lib/collector.rb', line 8

def sources
  @sources
end

Class Method Details

.register_after_update_callback(callback) ⇒ Object



14
15
16
# File 'lib/collector.rb', line 14

def self.register_after_update_callback(callback)
  Collector.instance.register_after_update_callback(callback)
end

.register_source(key, instance) ⇒ Object



10
11
12
# File 'lib/collector.rb', line 10

def self.register_source(key, instance)
  Collector.instance.register_source(key, instance)
end

.startObject



18
19
20
# File 'lib/collector.rb', line 18

def self.start
  instance.start
end

Instance Method Details

#publish_data(source, data) ⇒ Object



72
73
74
# File 'lib/collector.rb', line 72

def publish_data(source, data)
  Publisher.publish(source, data)
end

#register_after_update_callback(callback) ⇒ Object



68
69
70
# File 'lib/collector.rb', line 68

def register_after_update_callback(callback)
  @after_update_callback = callback
end

#register_source(key, instance) ⇒ Object



64
65
66
# File 'lib/collector.rb', line 64

def register_source(key, instance)
  @sources.merge!({ key => instance })
end

#startObject



27
28
29
30
31
32
33
34
35
36
# File 'lib/collector.rb', line 27

def start
  @sources.each do |source, instance|
    Thread.new do
      loop do
        update_in_thread(source, instance)
      end
    end
  end
  loop { sleep 1 }
end

#update_in_thread(source, instance) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/collector.rb', line 38

def update_in_thread(source, instance)
  time = Time.now
  puts "#{source} updating..."
  update_source(source, instance)
  elapsed_time = Time.now - time
  time_until_next_update = instance.update_interval - elapsed_time
  time_until_next_update = 0 if time_until_next_update < 0
  puts "#{source} done in #{elapsed_time} seconds, will update again in #{time_until_next_update} seconds (interval: #{instance.update_interval})."
  sleep time_until_next_update
rescue Exception => ex
  puts "Something failed outside the update_source method. #{ex.message}"
  puts ex.backtrace
end

#update_source(source, instance) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
# File 'lib/collector.rb', line 52

def update_source(source, instance)
  begin
    data = instance.fetch
    publish_data(source, data)
  ensure
    @after_update_callback.call
  end
rescue Exception => ex
  puts "Failed to update #{source}: #{ex.message}"
  puts ex.backtrace
end