class HonestPubsub::Publisher

Attributes

channel[R]
publisher[R]

Public Class Methods

instance() click to toggle source
# File lib/honest_pubsub/publisher.rb, line 8
def self.instance
  if @@publisher.nil?
    @@publisher = ::HonestPubsub::Publisher.new
  end
  @@publisher
end
new(exchange="honest") click to toggle source
# File lib/honest_pubsub/publisher.rb, line 15
def initialize(exchange="honest")
  @exchange = exchange
  @disabled = false
  @logger = ::HonestPubsub::Logger.new()

  @config = Configuration.configuration

  self
end

Public Instance Methods

enable(value) click to toggle source
# File lib/honest_pubsub/publisher.rb, line 25
def enable(value)
  @disabled = !value
  @disabled
end
publish(context, key, payload, enabled = true) click to toggle source
# File lib/honest_pubsub/publisher.rb, line 57
def publish(context, key, payload, enabled = true)
  routing_key = "#{@exchange}.#{key}"
  envelope = ::HonestPubsub::Message.new.serialize(context, key, payload)

  if @publisher.nil?
    start
  end

  if @disabled || @publisher.nil? || !enabled
    @logger.failed_publish(routing_key, {}, envelope)
  else
    tries = 2
    begin
      @publisher.publish(envelope.to_json, :persistent=>true, :mandatory=>true, :timestamp=>envelope[:ts], :content_type=>"application/json", :routing_key =>routing_key )
      @logger.log_publish(routing_key, envelope)
    rescue => e
      tries -= 1
      teardown
      start
      if tries > 0 && @publisher
        retry
      else
        @logger.failed_publish(routing_key, {}, envelope)
      end
    end

  end

end
start() click to toggle source
# File lib/honest_pubsub/publisher.rb, line 30
def start
  if !@config[:enabled].nil? && @config[:enabled] == false
    @disabled = true
    return
  end

  # grab server configuration from initialization file somewhere
  begin
    @connection = Bunny.new(Configuration.configuration[:connection])
    @connection.start

    @channel = @connection.create_channel
    @publisher = @channel.topic(@exchange, :durable=>true, :auto_delete=>false)

  rescue => e
    Airbrake.notify(e, parameters: {message: e.message}, environment_name: ENV['RAILS_ENV'] )
    return
  end


  @publisher.on_return do |return_info, properties, content|
    # contents are already transformed into message that we want to send
    @logger.failed_publish(return_info[:routing_key], properties, content)
  end

end
teardown() click to toggle source
# File lib/honest_pubsub/publisher.rb, line 87
def teardown
  @connection.close
  @publisher = nil
end