Merge commit 'origin/master'
[blip.rb.git] / blip.rb
blob4bd19e4c3b4ebcff22425be804abf59dd21f6ff0
1 require 'activeresource'
3 module Blip
4   class Connection < ActiveResource::Connection
5     def initialize(*a)
6       super *a
7       @default_header = { 'Content-Type' => format.mime_type, 'Accept' => format.mime_type, 'X-Blip-API' => '0.02' }
8     end
9   end
10   
11   class Resource < ActiveResource::Base
12     self.site = 'http://api.blip.pl'
13     self.format = :json
15     class << self
16       def connection(refresh = false)
17         @connection = Connection.new(site, format) if refresh || @connection.nil?
18         @connection.user = user if user
19         @connection.password = password if password
20         @connection.timeout = timeout if timeout
21         @connection
22       end
23       def const_missing name
24         const_set name, Class.new(Resource) unless const_defined? name
25         const_get name
26       end
27     
28     end
29     
30     def method_missing sym, *args
31       begin
32         super
33       rescue NoMethodError
34         name = sym.to_s
35         if @attributes.include?(name + '_path')
36           klass = Blip.const_get name.camelcase
37           klass.find(:one, :from => @attributes[name + '_path'])
38         end
39       end
40     end
42     def update
43       returning connection.put(stripped_path(prefix_options), attributes.to_json, self.class.headers) do |response|
44         load_attributes_from_response(response)
45       end
46     end
48     # Create (i.e., save to the remote service) the new resource.
49     def create
50       returning connection.post(stripped_path, attributes.to_json, self.class.headers) do |response|
51         self.id = id_from_response(response)
52         load_attributes_from_response(response)
53       end
54     end
55     
56     def stripped_path(*a) # strips back out the extension
57       element_path(*a).sub(/\/?\.#{self.class.format.extension}/, "")
58     end
60   end
61   
62   class << self
63     def const_missing name
64       const_set name, Class.new(Resource) unless const_defined? name
65       const_get name
66     end
67     
68     def method_missing name, *args
69       Resource.send name, args
70     end
71   end
72 end