Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

root/trunk/activeresource/lib/active_resource/connection.rb

Revision 5068, 2.0 kB (checked in by rick, 4 years ago)

Basic validation support [Rick Olson]

Line 
1 require 'net/https'
2 require 'date'
3 require 'time'
4 require 'uri'
5
6 module ActiveResource
7   class ConnectionError < StandardError
8     attr_reader :response
9
10     def initialize(response, message = nil)
11       @response = response
12       @message  = message
13     end
14
15     def to_s
16       "Failed with #{response.code}"
17     end
18   end
19
20   class ClientError < ConnectionError
21   end
22
23   class ServerError < ConnectionError
24   end
25
26   class ResourceNotFound < ClientError
27   end
28
29   class Connection
30     attr_accessor :site
31
32     class << self
33       def requests
34         @@requests ||= []
35       end
36      
37       def default_header
38         class << self ; attr_reader :default_header end
39         @default_header = { 'Content-Type' => 'application/xml' }
40       end
41     end
42
43     def initialize(site)
44       @site = site
45     end
46
47     def get(path)
48       Hash.create_from_xml(request(:get, path).body)
49     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     end
58
59     def post(path, body = '')
60       request(:post, path, body, self.class.default_header)
61     end
62
63     private
64       def request(method, *arguments)
65         handle_response(http.send(method, *arguments))
66       end
67
68       def handle_response(response)
69         case response.code.to_i
70           when 200...400
71             response
72           when 404
73             raise(ResourceNotFound.new(response))
74           when 400
75             raise(ResourceInvalid.new(response))
76           when 401...500
77             raise(ClientError.new(response))
78           when 500...600
79             raise(ServerError.new(response))
80           else
81             raise(ConnectionError.new(response, "Unknown response code: #{response.code}"))
82         end
83       end
84
85       def http
86         unless @http
87           @http             = Net::HTTP.new(@site.host, @site.port)
88           @http.use_ssl     = @site.is_a?(URI::HTTPS)
89           @http.verify_mode = OpenSSL::SSL::VERIFY_NONE if @http.use_ssl
90         end
91
92         @http
93       end
94   end
95 end
Note: See TracBrowser for help on using the browser.