Module: Ey::Core::Subscribable

Included in:
Client::Request, Client::Task
Defined in:
lib/ey-core/subscribable.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



2
3
4
# File 'lib/ey-core/subscribable.rb', line 2

def self.included(klass)
  klass.send(:attribute, :read_channel)
end

Instance Method Details

#read_channel_uriObject



6
7
8
# File 'lib/ey-core/subscribable.rb', line 6

def read_channel_uri
  self.read_channel && Addressable::URI.parse(self.read_channel)
end

#subscribe(&block) ⇒ Object



10
11
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
44
45
46
47
48
# File 'lib/ey-core/subscribable.rb', line 10

def subscribe(&block)
  return false unless read_channel_uri

  gem 'faye', '~> 1.1'
  require 'faye' # soft dependency

  uri = read_channel_uri

  resource = self

  url          = uri.omit(:query).to_s
  token        = uri.query_values["token"]
  subscription = uri.query_values["subscription"]

  EM.run do
    client = Faye::Client.new(url)
    client.set_header("Authorization", "Token #{token}")

    deferred = client.subscribe(subscription) do |message|
      block.call(JSON.load(message))
    end

    deferred.callback do
      block.call({"meta" => true, "created_at" => Time.now,"message" => "successfully connected to log streaming service\n"})
    end

    deferred.errback do |error|
      block.call({"meta" => true, "created_at" => Time.now, "message" => "failed to stream output: #{error.inspect}\n"})
      EM.stop_event_loop
    end

    EventMachine::PeriodicTimer.new(5) do
      if resource.reload.ready?
        block.call({"meta" => true, "created_at" => Time.now, "message" => "#{resource} finished"})
        EM.stop_event_loop
      end
    end
  end
end