Sha256: 0e163781d0139afa588ed0538b3cf0029f866560205342b3c4a1d98cdd26b38a

Contents?: true

Size: 1.42 KB

Versions: 3

Compression:

Stored size: 1.42 KB

Contents

require "json"

module RisingDragon
  module SQS
    class Emitter
      def initialize
        @handlers = {}
      end

      def register(event_name, handler_class)
        unless event_name.is_a?(String)
          raise "event_name must be String, but it's #{event_name.class}. event_name: #{event_name}"
        end
        if @handlers[event_name]
          raise "RisingDragon::SQS::Emitter accepts only one callback per event. event_name: #{event_name}"
        end
        @handlers[event_name] = handler_class
      end

      def unregister(event_name)
        unless event_name.is_a?(String)
          raise "event_name must be String, but it's #{event_name.class}. event_name: #{event_name}"
        end

        @handlers.delete(event_name)
      end

      def ignore(event_name)
        @handlers.delete(event_name)
      end

      def list
        @handlers.keys
      end

      def emit_event(event)
        handler = @handlers[event.type]
        handler.new.handle(event) if handler

        nil
      end

      def event_from_json(body)
        msg = JSON.parse(body["Message"])

        id = msg["id"]
        type = msg["type"]
        timestamp = Time.at(msg["timestamp"] / 1000.0)
        data = msg["data"]

        ::RisingDragon::Event.new(id: id, type: type, timestamp: timestamp, data: data)
      end

      def emit_sns_msg(body)
        event = event_from_json(body)
        emit_event(event)
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rising_dragon-0.2.1 lib/rising_dragon/sqs/emitter.rb
rising_dragon-0.2.0 lib/rising_dragon/sqs/emitter.rb
rising_dragon-0.1.1 lib/rising_dragon/sqs/emitter.rb