connection.rb 2.2 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
  class ClientError < ConnectionError;  end  # 4xx Client Error
  class ResourceNotFound < ClientError; end  # 404 Not Found
  class ResourceConflict < ClientError; end  # 409 Conflict
23

24
  class ServerError < ConnectionError;  end  # 5xx Server Error
25

26 27

  class Connection
28 29
    attr_accessor :site

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

    def initialize(site)
      @site = site
    end
44

45 46 47
    def get(path)
      Hash.create_from_xml(request(:get, path).body)
    end
48

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

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

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

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

66
      def handle_response(response)
67
        case response.code.to_i
68
          when 200...400
69 70 71
            response
          when 404
            raise(ResourceNotFound.new(response))
72 73
          when 400
            raise(ResourceInvalid.new(response))
74 75
          when 409
            raise(ResourceConflict.new(response))
76
          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