Sha256: 83fdb6e6ff237bf3d11748aa7bfb03d35903432e773938cfe12564831caf5570

Contents?: true

Size: 1.6 KB

Versions: 12

Compression:

Stored size: 1.6 KB

Contents

require 'em-websocket'
require 'yajl'

require 'ganymed/websocket'
require 'ganymed/websocket/authentication'
require 'ganymed/websocket/subscribe'
require 'ganymed/websocket/metadata'
require 'ganymed/websocket/query'

module Ganymed
  class Websocket
    class Connection < EventMachine::WebSocket::Connection
      attr_accessor :config, :db

      def self.command(command)
        @commands ||= []
        @commands << command
      end

      def self.commands
        @commands
      end

      include Authentication
      include Metadata
      include Subscribe
      include Query

      def peer
        sin = Socket.unpack_sockaddr_in(get_peername)
        "#{sin[1]}:#{sin[0]}"
      rescue
        "unknown"
      end

      def convert(data)
        if data.is_a?(Hash)
          data
        elsif data.is_a?(Array)
          data.map {|elem| convert(elem)}
        else
          if data.respond_to?(:as_json)
            data.as_json
          elsif data.respond_to?(:to_h)
            data.to_h
          elsif data.respond_to?(:to_a)
            data.to_a
          else
            data
          end
        end
      end

      def send(type, data)
        super(Yajl::Encoder.encode({type.to_s => convert(data)}))
      end

      def trigger_on_message(data)
        data = Yajl::Parser.parse(data)
        data.each do |command, data|
          log.debug("command #{command}(#{data.inspect})")
          if self.class.commands.include?(command.to_sym)
            __send__(command.to_sym, data)
          else
            send(:error, "invalid command")
          end
        end
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
ganymed-0.3.4 lib/ganymed/websocket/connection.rb
ganymed-0.3.3 lib/ganymed/websocket/connection.rb
ganymed-0.3.2 lib/ganymed/websocket/connection.rb
ganymed-0.3.1 lib/ganymed/websocket/connection.rb
ganymed-0.3.0 lib/ganymed/websocket/connection.rb
ganymed-0.2.3 lib/ganymed/websocket/connection.rb
ganymed-0.2.2 lib/ganymed/websocket/connection.rb
ganymed-0.2.1 lib/ganymed/websocket/connection.rb
ganymed-0.2.0 lib/ganymed/websocket/connection.rb
ganymed-0.1.2 lib/ganymed/websocket/connection.rb
ganymed-0.1.1 lib/ganymed/websocket/connection.rb
ganymed-0.1.0 lib/ganymed/websocket/connection.rb