require 'hashie' require 'bunny' require 'hat/configurable' module Hat module Publisher include Configurable has_configuration :publisher, { middlewares: [], options: { persistent: false, mandatory: false }, default_direct_exchange: 'hat.direct', default_topic_exchange: 'hat.topic' } def self.channel unless @connection @connection = Bunny.new @connection.start end @channel ||= @connection.create_channel end def self.publish(type, exchange, message, queue=nil, options={}, exchange_options={}) options.merge(routing_key: queue) if queue config.publisher.middlewares.each { |m| message = m.call(message) } channel.send(type, exchange, exchange_options.merge(config.exchange)). publish(message, options.merge(config.publisher.options)) true end def self.direct(queue, message, options={}) publish(:direct, (options.delete(:exchange) || config.publisher.default_direct_exchange), message, queue, options) end def self.topic(queue, message, options={}) publish(:topic, (options.delete(:exchange) || config.publisher.default_topic_exchange), message, queue, options) end end end