Sha256: b0a4bcd4fbfa570f937a4f783ac83fc7ac3a71674843cadeb89c57fe18a06284

Contents?: true

Size: 1.49 KB

Versions: 1

Compression:

Stored size: 1.49 KB

Contents

module Smoke
  class Request # :nodoc:
    class Failure < Exception # :nodoc:
      attr_reader :uri
      
      def initialize(uri, msg)
        @uri = URI.parse(uri)
        Smoke.log.error "Smoke Request: Failed to get from #{@uri} (#{msg})"
      end
    end
    
    SUPPORTED_TYPES = %w(json xml javascript excel)
    @@request_options = {
      :user_agent       => Smoke.config[:user_agent],
      :accept_encoding  => "gzip, deflate"
    }
    
    attr_reader :uri, :content_type, :body
       
    def initialize(uri, options = {})
      @uri, @options = uri, options
      dispatch
    end
    
    def type
      @type ||= @options[:type] || (SUPPORTED_TYPES.detect{|t| @content_type =~ /#{t}/ } || "unknown").to_sym
    end
    
    private
    def dispatch
      get = Smoke::Cache.fetch @uri, @@request_options
      @body = get[:body]
      @content_type = get[:content_type]
      
      parse! unless @options[:raw_response]
      
    rescue RestClient::Exception => e
      Failure.new(@uri, e)
    end
    
    def parse!
      case type
        when :json, :javascript
          @body = ::Crack::JSON.parse(@body).symbolize_keys!
        when :xml
          @body = ::Crack::XML.parse(@body).symbolize_keys!
        when :excel
          # Convert the excel document into an XML document
          doc = @body
          ::Crack::XML.parse().symbolize_keys!
        when :unknown
          Smoke.log.warn "Smoke Request: Format unknown for #{@uri} (#{@content_type})"
      end      
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
smoke-0.5.17 lib/smoke/request.rb