Sha256: ecc78e933e91d77a2570dd620043bbfa9ff54d2b91a5b7f3cf7c454c78f21dfe

Contents?: true

Size: 1.37 KB

Versions: 49

Compression:

Stored size: 1.37 KB

Contents

module RestPack::Service
  class Response
    attr_accessor :result, :errors, :status

    def initialize
      @result = {}
      @errors = {}
    end

    def success?
      @errors.empty? and @status == :ok
    end

    def code
      Status.from_status(status)
    end

    def add_error(field, message)
      @errors[field] ||= []
      @errors[field] << message
    end

    def self.from_rest(rest_response)
      response = new
      response.status = Status.from_code(rest_response.code)
      response.result = Yajl::Parser.parse(rest_response.body, :symbolize_keys => true)

      if response.result[:errors]
        response.result[:errors].each do |field, errors|
          response.errors[field.to_sym] = errors
        end

        response.result.delete :errors
      end

      response
    end

    class Status
      @@map = {
        200 => :ok,
        401 => :unauthorized,
        403 => :forbidden,
        404 => :not_found,
        422 => :unprocessable_entity,
        500 => :internal_service_error
      }

      def self.from_code(code)
        if @@map.has_key?(code)
          @@map[code]
        else
          raise "Invalid Status Code: #{code}"
        end
      end

      def self.from_status(status)
        if @@map.has_value?(status)
          @@map.key(status)
        else
          raise "Invalid Status: #{status}"
        end
      end
    end
  end
end

Version data entries

49 entries across 49 versions & 1 rubygems

Version Path
restpack_service-0.0.83 lib/restpack_service/response.rb
restpack_service-0.0.82 lib/restpack_service/response.rb
restpack_service-0.0.81 lib/restpack_service/response.rb
restpack_service-0.0.80 lib/restpack_service/response.rb
restpack_service-0.0.79 lib/restpack_service/response.rb
restpack_service-0.0.78 lib/restpack_service/response.rb
restpack_service-0.0.77 lib/restpack_service/response.rb
restpack_service-0.0.76 lib/restpack_service/response.rb
restpack_service-0.0.75 lib/restpack_service/response.rb
restpack_service-0.0.74 lib/restpack_service/response.rb
restpack_service-0.0.73 lib/restpack_service/response.rb
restpack_service-0.0.72 lib/restpack_service/response.rb
restpack_service-0.0.71 lib/restpack_service/response.rb
restpack_service-0.0.70 lib/restpack_service/response.rb
restpack_service-0.0.69 lib/restpack_service/response.rb
restpack_service-0.0.68 lib/restpack_service/response.rb
restpack_service-0.0.67 lib/restpack_service/response.rb
restpack_service-0.0.66 lib/restpack_service/response.rb
restpack_service-0.0.65 lib/restpack_service/response.rb
restpack_service-0.0.64 lib/restpack_service/response.rb