Sha256: c649f66cb4acb12f92f7a8e7b5eae8cbacebdb7a2c654025bf49c40114e1b91d

Contents?: true

Size: 1.52 KB

Versions: 2

Compression:

Stored size: 1.52 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)
    attr_reader :uri, :content_type, :body, :type
       
    def initialize(uri, *options)
      @uri = uri
      @options = options
      dispatch
    end
    
    private
    def dispatch
      opts = {
        "User-Agent"      => Smoke.config[:user_agent],
        "Accept-Encoding" => "gzip"
      }
      Thread.new {
        open(@uri, opts) do |request|
          @content_type = request.content_type
          request = Zlib::GzipReader.new(request) if request.content_encoding.include? "gzip"
          @body = request.read
        end
      }.join
      
      unless @options.include?(:raw_response)
        present!
      end
    rescue OpenURI::HTTPError => e
      Failure.new(@uri, e)
    end
    
    def present!
      set_type
      parse!
    end
    
    def set_type
      @type = (SUPPORTED_TYPES.detect{|t| @content_type =~ /#{t}/ } || "unknown").to_sym
    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 :unknown
          Smoke.log.warn "Smoke Request: Format unknown for #{@uri} (#{@content_type})"
      end      
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
benschwarz-smoke-0.3.7 lib/smoke/request.rb
benschwarz-smoke-0.3.9 lib/smoke/request.rb