Sha256: 16f1a57b5631d98da4d2bad867715f07ac526c5fef9239e7497771ef8cacf181

Contents?: true

Size: 1.29 KB

Versions: 24

Compression:

Stored size: 1.29 KB

Contents

module Ey::Core::Subscribable
  def self.included(klass)
    klass.send(:attribute, :read_channel)
  end

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

  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 subscribed"})
      end

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

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

Version data entries

24 entries across 24 versions & 2 rubygems

Version Path
ey-core-3.1.2 lib/ey-core/subscribable.rb
ey-core-3.1.1 lib/ey-core/subscribable.rb
ey-core-3.1.0 lib/ey-core/subscribable.rb
ey-core-3.0.5 lib/ey-core/subscribable.rb
ey-core-3.0.4 lib/ey-core/subscribable.rb
ey-core-3.0.3 lib/ey-core/subscribable.rb
ey-core-3.0.2 lib/ey-core/subscribable.rb
ey-core-3.0.1 lib/ey-core/subscribable.rb
ey-core-3.0.0 lib/ey-core/subscribable.rb
ey-pro-cli-0.0.17 lib/vendor/core/ey-core/subscribable.rb
ey-pro-cli-0.0.16 lib/vendor/core/ey-core/subscribable.rb
ey-pro-cli-0.0.15 lib/vendor/core/ey-core/subscribable.rb
ey-pro-cli-0.0.14 lib/vendor/core/ey-core/subscribable.rb
ey-pro-cli-0.0.13 lib/vendor/core/ey-core/subscribable.rb
ey-pro-cli-0.0.12 lib/vendor/core/ey-core/subscribable.rb
ey-pro-cli-0.0.11 lib/vendor/core/ey-core/subscribable.rb
ey-pro-cli-0.0.10 lib/vendor/core/ey-core/subscribable.rb
ey-pro-cli-0.0.9 lib/vendor/core/ey-core/subscribable.rb
ey-pro-cli-0.0.8 lib/vendor/core/ey-core/subscribable.rb
ey-pro-cli-0.0.7 lib/vendor/core/ey-core/subscribable.rb