connection.rb 2.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
require 'net/https'
require 'date'
require 'time'
require 'uri'

module ActiveResource
  class ConnectionError < StandardError
    attr_reader :response

    def initialize(response, message = nil)
      @response = response
      @message  = message
    end
14

15 16 17 18
    def to_s
      "Failed with #{response.code}"
    end
  end
19

20 21 22 23 24
  class ClientError < ConnectionError
  end

  class ServerError < ConnectionError
  end
25

26 27 28 29
  class ResourceNotFound < ClientError
  end

  class Connection
30 31
    attr_accessor :site

32 33 34 35
    class << self
      def requests
        @@requests ||= []
      end
36 37 38 39 40
      
      def default_header
        class << self ; attr_reader :default_header end
        @default_header = { 'Content-Type' => 'application/xml' }
      end
41 42 43 44 45
    end

    def initialize(site)
      @site = site
    end
46

47 48 49
    def get(path)
      Hash.create_from_xml(request(:get, path).body)
    end
50

51
    def delete(path)
52
      request(:delete, path, self.class.default_header)
53
    end
54 55

    def put(path, body = '')
56
      request(:put, path, body, self.class.default_header)
57 58
    end

59
    def post(path, body = '')
60
      request(:post, path, body, self.class.default_header)
61
    end
62

63 64
    private
      def request(method, *arguments)
65 66
        handle_response(http.send(method, *arguments))
      end
67

68
      def handle_response(response)
69
        case response.code.to_i
70
          when 200...400
71 72 73
            response
          when 404
            raise(ResourceNotFound.new(response))
74 75 76
          when 400
            raise(ResourceInvalid.new(response))
          when 401...500
77 78 79 80 81 82 83 84 85 86 87 88 89 90
            raise(ClientError.new(response))
          when 500...600
            raise(ServerError.new(response))
          else
            raise(ConnectionError.new(response, "Unknown response code: #{response.code}"))
        end
      end

      def http
        unless @http
          @http             = Net::HTTP.new(@site.host, @site.port)
          @http.use_ssl     = @site.is_a?(URI::HTTPS)
          @http.verify_mode = OpenSSL::SSL::VERIFY_NONE if @http.use_ssl
        end
91

92 93 94
        @http
      end
  end
95
end