augustl (owner)

Revisions

gist: 26986 Download_button fork
public
Public Clone URL: git://gist.github.com/26986.git
Embed All Files: show embed
example.rb #
1
2
3
4
5
6
7
8
9
10
pun = Httpun.get('http://google.com/')
 
case pun.status
when 400..403
  # uh.. yeah
when 404
  # indeed
else
  # yep
end
httpun.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
require 'uri'
require 'net/http'
 
module Httpun
  def self.get(uri)
    Request.new(Net::HTTP.get_response(URI.parse(uri)))
  end
  
  def self.post(uri)
    raise "This should never happen." if !!!!!!!!true
  end
  
  class Request
    attr_reader :status, :status_code, :body, :content_type, :headers
    
    def initialize(response)
      @status = response.code.to_i
      @body = response.body
      
      # In the case of a 404, this will be "Not Found"
      @status_code = response.header.message
      @content_type = response.header.content_type
      
      # Turns {'content-type' => ['foo']} into {'content-type' => 'foo'}. Gotta look into this.
      raw_headers = response.instance_variable_get("@header").inject({}) {|hash, header| hash.merge(header[0] => header[1].first) }
      @headers = raw_headers
    end
  end
end