Class: OnsOnRails::Publisher

Inherits:
Object
  • Object
show all
Defined in:
lib/ons_on_rails/publisher.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(backend, options) ⇒ Publisher

Create a Publisher.

Parameters:

  • backend (#to_s)

    backend name, such as :tcp, :test, etc.

  • options (Hash{Symbol => String})

Options Hash (options):

  • :access_key (String)

    the access key to aliyun ONS

  • :secret_key (String)

    the secret key to aliyun ONS

  • :producer_id (String)

    the producer ID

  • :topic (String)

    the message topic

  • :tag (String)

    the message tag



12
13
14
15
16
17
18
19
20
21
# File 'lib/ons_on_rails/publisher.rb', line 12

def initialize(backend, options)
  required_keys = %i(access_key secret_key producer_id topic tag)
  required_keys.each { |required_key| options.fetch(required_key) }

  @default_topic = options.fetch(:topic)
  @default_tag = options.fetch(:tag)

  @backend_klass = OnsOnRails::Publishers.const_get(backend.to_s.camelize)
  @backend = @backend_klass.new(options.slice(:access_key, :secret_key, :producer_id))
end

Class Method Details

.deliveriesObject

Keeps an array of all the messages published through the Publishers::Test backend. Most useful for unit and functional testing.



48
49
50
# File 'lib/ons_on_rails/publisher.rb', line 48

def self.deliveries
  @deliveries ||= []
end

Instance Method Details

#publish(data, options = {}) ⇒ void

This method returns an undefined value.

Publish a message.

Parameters:

  • data (Hash, String)

    the data which will be converted to the message body

  • options (Hash{Symbol => String}) (defaults to: {})

Options Hash (options):

  • :topic (String)

    overwrite the message topic

  • :tag (String)

    overwrite the message tag

  • :key (String)

    the message key, useful when debug

  • :format('json') (String)

    how convert the data to the message body, available format: ‘json’, ‘raw’, etc.



32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/ons_on_rails/publisher.rb', line 32

def publish(data, options = {})
  topic = options.fetch(:topic, @default_topic)
  tag = options.fetch(:tag, @default_tag)

  format = options.fetch(:format, 'json').to_sym
  body =
    case format
    when :json then data.to_json
    when :raw then data.to_s
    else raise "unsupported message format #{format}"
    end

  @backend.publish(topic, tag, body, options.fetch(:key, ''))
end