Sha256: 6686a4e31d0eaa6eb5d2ca3cd9b2b53677ceebbad2dda0ac283e026d9e4b7535

Contents?: true

Size: 1.35 KB

Versions: 4

Compression:

Stored size: 1.35 KB

Contents

require 'saorin'
require 'saorin/error'
require 'saorin/utility'
require 'multi_json'

module Saorin
  class Response
    attr_accessor :version, :result, :error, :id

    def initialize(options = {})
      @version = options[:version] || Saorin::JSON_RPC_VERSION
      @result = options[:result]
      @error = options[:error]
      @id = options[:id]
    end

    def error?
      !!@error
    end

    def valid?
      return false unless !(@result && @error)
      return false unless [String].any? { |type| @version.is_a? type }
      return false unless [Object].any? { |type| @result.is_a? type }
      return false unless [Saorin::Error, Hash, NilClass].any? { |type| @error.is_a? type }
      return false unless [String, Numeric, NilClass].any? { |type| @id.is_a? type }
      return false unless @version == JSON_RPC_VERSION
      true
    end

    def validate
      raise Saorin::InvalidResponse unless valid?
    end

    def to_h
      h = {}
      h['jsonrpc'] = @version
      h['result'] = @result unless error?
      h['error'] = @error if error?
      h['id'] = id
      h
    end

    def to_json(*args)
      options = args.last.is_a?(::Hash) ? args.pop : {}
      MultiJson.dump to_h, options
    end

    def self.from_hash(hash)
      raise Saorin::InvalidResponse unless hash.is_a?(::Hash)
      new Saorin::Utility.symbolized_keys(hash)
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
saorin-0.3.2 lib/saorin/response.rb
saorin-0.3.1 lib/saorin/response.rb
saorin-0.3.0 lib/saorin/response.rb
saorin-0.2.0 lib/saorin/response.rb