Sha256: af3dafbf4f7d40c516f6d83d564a4ed097c42756f392facd085d385a5e4a6564

Contents?: true

Size: 1.76 KB

Versions: 1

Compression:

Stored size: 1.76 KB

Contents

module Mailgun
  # A Mailgun::Response object is instantiated for each response generated
  # by the Client request. The Response object supports deserialization of
  # the JSON result. Or, if you prefer JSON or YAML formatting, call the
  # method for conversion.
  #
  # See the Github documentation for full examples.
  class Response
    # All responses have a payload and a code corresponding to http, though
    #   slightly different
    attr_accessor :body, :code

    ResponseHash = Struct.new(:body, :code)
    def self.from_hash(h)
      # Create a "fake" response object with the data passed from h
      self.new ResponseHash.new(h[:body], h[:code])
    end

    def initialize(response)
      @body = response.body
      @code = response.code
    end

    # Return response as Ruby Hash
    #
    # @return [Hash] A standard Ruby Hash containing the HTTP result.

    def to_h
      JSON.parse(@body)
    rescue => err
      raise ParseError.new(err), err
    end

    # Replace @body with Ruby Hash
    #
    # @return [Hash] A standard Ruby Hash containing the HTTP result.
    def to_h!
      @body = JSON.parse(@body)
    rescue => err
      raise ParseError.new(err), err
    end

    # Return response as Yaml
    #
    # @return [String] A string containing response as YAML
    def to_yaml
      YAML.dump(to_h)
    rescue => err
      raise ParseError.new(err), err
    end

    # Replace @body with YAML
    #
    # @return [String] A string containing response as YAML
    def to_yaml!
      @body = YAML.dump(to_h)
    rescue => err
      raise ParseError.new(err), err
    end
    
    # Returns true if response code is 2xx
    # 
    # @return [Boolean] A boolean that binarizes the response code result.
    def success?
      (200..299).include?(code)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mailgun-ruby-1.2.15 lib/mailgun/response.rb