base.rb 13.1 KB
Newer Older
1
require 'active_resource/connection'
2 3
require 'cgi'
require 'set'
4 5 6

module ActiveResource
  class Base
7
    # The logger for diagnosing and tracing ARes calls.
8 9
    cattr_accessor :logger

10
    class << self
11
      # Gets the URI of the resource's site
12 13 14 15 16 17 18
      def site
        if defined?(@site)
          @site
        elsif superclass != Object and superclass.site
          superclass.site.dup.freeze
        end
      end
J
Jeremy Kemper 已提交
19

20
      # Set the URI for the REST resources
21
      def site=(site)
22
        @connection = nil
23
        @site = create_site_uri_from(site)
24 25
      end

26
      # Base connection to remote service
27 28 29 30
      def connection(refresh = false)
        @connection = Connection.new(site) if refresh || @connection.nil?
        @connection
      end
31

32 33 34 35
      # Do not include any modules in the default element name. This makes it easier to seclude ARes objects
      # in a separate namespace without having to set element_name repeatedly.
      attr_accessor_with_default(:element_name)    { to_s.split("::").last.underscore } #:nodoc:

36 37 38 39 40
      attr_accessor_with_default(:collection_name) { element_name.pluralize } #:nodoc:
      attr_accessor_with_default(:primary_key, 'id') #:nodoc:
      
      # Gets the resource prefix
      #  prefix/collectionname/1.xml
41 42 43
      def prefix(options={})
        default = site.path
        default << '/' unless default[-1..-1] == '/'
44
        # generate the actual method based on the current site path
45
        self.prefix = default
46 47
        prefix(options)
      end
48

49 50 51 52 53
      def prefix_source
        prefix # generate #prefix and #prefix_source methods first
        prefix_source
      end

54 55
      # Sets the resource prefix
      #  prefix/collectionname/1.xml
56
      def prefix=(value = '/')
57
        # Replace :placeholders with '#{embedded options[:lookups]}'
58
        prefix_call = value.gsub(/:\w+/) { |key| "\#{options[#{key}]}" }
59 60 61

        # Redefine the new methods.
        code = <<-end_code
62 63
          def prefix_source() "#{value}" end
          def prefix(options={}) "#{prefix_call}" end
64 65
        end_code
        silence_warnings { instance_eval code, __FILE__, __LINE__ }
66
      rescue
67
        logger.error "Couldn't set prefix: #{$!}\n  #{code}"
68
        raise
69
      end
70

71
      alias_method :set_prefix, :prefix=  #:nodoc:
72

73 74
      alias_method :set_element_name, :element_name=  #:nodoc:
      alias_method :set_collection_name, :collection_name=  #:nodoc:
75

76 77 78 79 80 81 82 83 84
      # Gets the element path for the given ID.  If no query_options are given, they are split from the prefix options:
      #
      # Post.element_path(1) # => /posts/1.xml
      # Comment.element_path(1, :post_id => 5) # => /posts/5/comments/1.xml
      # Comment.element_path(1, :post_id => 5, :active => 1) # => /posts/5/comments/1.xml?active=1
      # Comment.element_path(1, {:post_id => 5}, {:active => 1}) # => /posts/5/comments/1.xml?active=1
      def element_path(id, prefix_options = {}, query_options = nil)
        prefix_options, query_options = split_options(prefix_options) if query_options.nil?
        "#{prefix(prefix_options)}#{collection_name}/#{id}.xml#{query_string(query_options)}"
85
      end
86

87 88 89 90 91 92 93 94 95
      # Gets the collection path.  If no query_options are given, they are split from the prefix options:
      #
      # Post.collection_path # => /posts.xml
      # Comment.collection_path(:post_id => 5) # => /posts/5/comments.xml
      # Comment.collection_path(:post_id => 5, :active => 1) # => /posts/5/comments.xml?active=1
      # Comment.collection_path({:post_id => 5}, {:active => 1}) # => /posts/5/comments.xml?active=1
      def collection_path(prefix_options = {}, query_options = nil)
        prefix_options, query_options = split_options(prefix_options) if query_options.nil?
        "#{prefix(prefix_options)}#{collection_name}.xml#{query_string(query_options)}"
96
      end
97

98
      alias_method :set_primary_key, :primary_key=  #:nodoc:
99

100 101 102 103 104 105 106 107 108 109 110
      # Create a new resource instance and request to the remote service
      # that it be saved.  This is equivalent to the following simultaneous calls:
      #
      #   ryan = Person.new(:first => 'ryan')
      #   ryan.save
      #
      # The newly created resource is returned.  If a failure has occurred an
      # exception will be raised (see save).  If the resource is invalid and
      # has not been saved then <tt>resource.valid?</tt> will return <tt>false</tt>,
      # while <tt>resource.new?</tt> will still return <tt>true</tt>.
      #      
111 112
      def create(attributes = {})
        returning(self.new(attributes)) { |res| res.save }        
113 114
      end

115
      # Core method for finding resources.  Used similarly to Active Record's find method.
116 117 118 119 120 121 122
      #  Person.find(1)                                        # => GET /people/1.xml
      #  Person.find(:all)                                     # => GET /people.xml
      #  Person.find(:all, :title => "CEO")                    # => GET /people.xml?title=CEO
      #  Person.find(:managers)                                # => GET /people/managers.xml
      #  Person.find(:all, :from => "/companies/1/people.xml") # => GET /companies/1/people.xml
      #  Person.find("/companies/1/manager.xml")               # => GET /companies/1/manager.xml
      #  StreetAddress.find(1, :person_id => 1)                # => GET /people/1/street_addresses/1.xml
123
      def find(*arguments)
124 125
        scope   = arguments.slice!(0)
        options = arguments.slice!(0) || {}
126 127

        case scope
128 129
          when :all   then find_every(options)
          when :first then find_every(options).first
130
          when Symbol then instantiate_collection(get(scope, options))
131
          else             find_single(scope, options)
132 133
        end
      end
134

135 136
      def delete(id, options = {})
        connection.delete(element_path(id, options))
137 138
      end

139
      # Evalutes to <tt>true</tt> if the resource is found.
140 141 142 143 144 145
      def exists?(id, options = {})
        id && !find_single(id, options).nil?
      rescue ActiveResource::ResourceNotFound
        false
      end

146
      private
147
        # Find every resource.
148
        def find_every(options)
149
          from = options.delete(:from)
150
          prefix_options, query_options = split_options(options)
151 152 153
          from ||= collection_path(prefix_options, query_options)

          instantiate_collection(connection.get(from) || [])
154 155 156
        end
        
        def instantiate_collection(collection, prefix_options = {})
157
          collection.collect! do |element|
158
            returning new(element) do |resource|
159 160 161
              resource.prefix_options = prefix_options
            end
          end
162
        end
163

164 165
        # Find a single resource.
        #  { :person => person1 }
166
        def find_single(scope, options)
167
          prefix_options, query_options = split_options(options)
168 169 170
          from = scope.to_s.include?("/") ? scope : element_path(scope, prefix_options, query_options)

          returning new(connection.get(from)) do |resource|
171 172
            resource.prefix_options = prefix_options
          end
173
        end
174

175
        # Accepts a URI and creates the site URI from that.
176
        def create_site_uri_from(site)
177
          site.is_a?(URI) ? site.dup : URI.parse(site)
178
        end
179

180
        # contains a set of the current prefix parameters.
181 182 183 184
        def prefix_parameters
          @prefix_parameters ||= prefix_source.scan(/:\w+/).map { |key| key[1..-1].to_sym }.to_set
        end

185
        # Builds the query string for the request.
186
        def query_string(options)
187 188 189 190 191 192 193 194 195 196 197
          "?#{options.to_query}" unless options.empty? 
        end

        # split an option hash into two hashes, one containing the prefix options, 
        # and the other containing the leftovers.
        def split_options(options = {})
          prefix_options = {}; query_options = {}
          options.each do |key, value|
            (prefix_parameters.include?(key) ? prefix_options : query_options)[key] = value
          end
          [prefix_options, query_options]
198
        end
199 200
    end

201 202
    attr_accessor :attributes #:nodoc:
    attr_accessor :prefix_options #:nodoc:
203

204 205 206
    def initialize(attributes = {})
      @attributes     = {}
      @prefix_options = {}
207
      load(attributes)
208
    end
209

210
    # Is the resource a new object?
211
    def new?
212 213 214
      id.nil?
    end

215
    # Get the id of the object.
216
    def id
217
      attributes[self.class.primary_key]
218
    end
219

220
    # Set the id of the object.
221
    def id=(id)
222
      attributes[self.class.primary_key] = id
223
    end
224

225
    # True if and only if +other+ is the same object or is an instance of the same class, is not +new?+, and has the same +id+.
226 227 228 229 230 231 232 233 234 235 236 237 238 239
    def ==(other)
      other.equal?(self) || (other.instance_of?(self.class) && !other.new? && other.id == id)
    end

    # Delegates to ==
    def eql?(other)
      self == other
    end

    # Delegates to id in order to allow two resources of the same type and id to work with something like:
    #   [Person.find(1), Person.find(2)] & [Person.find(1), Person.find(4)] # => [Person.find(1)]
    def hash
      id.hash
    end
240 241 242 243 244 245 246
    
    def dup
      returning new do |resource|
        resource.attributes     = @attributes
        resource.prefix_options = @prefix_options
      end
    end
247

248 249 250
    # Delegates to +create+ if a new object, +update+ if its old. If the response to the save includes a body,
    # it will be assumed that this body is XML for the final object as it looked after the save (which would include
    # attributes like created_at that wasn't part of the original submit).
251
    def save
252
      new? ? create : update
253 254
    end

255
    # Delete the resource.
256
    def destroy
257
      connection.delete(element_path)
258
    end
259

260
    # Evaluates to <tt>true</tt> if this resource is found.
261 262 263 264
    def exists?
      !new? && self.class.exists?(id, prefix_options)
    end

265
    # Convert the resource to an XML string
266 267
    def to_xml(options={})
      attributes.to_xml({:root => self.class.element_name}.merge(options))
268
    end
269 270 271

    # Reloads the attributes of this object from the remote web service.
    def reload
272
      self.load(self.class.find(id, @prefix_options).attributes)
273 274 275 276 277
    end

    # Manually load attributes from a hash. Recursively loads collections of
    # resources.
    def load(attributes)
J
Jeremy Kemper 已提交
278
      raise ArgumentError, "expected an attributes Hash, got #{attributes.inspect}" unless attributes.is_a?(Hash)
279
      @prefix_options, attributes = split_options(attributes)
280 281 282 283 284 285 286
      attributes.each do |key, value|
        @attributes[key.to_s] =
          case value
            when Array
              resource = find_or_create_resource_for_collection(key)
              value.map { |attrs| resource.new(attrs) }
            when Hash
287 288
              resource = find_or_create_resource_for(key)
              resource.new(value)
289 290 291 292
            else
              value.dup rescue value
          end
      end
293 294 295
      self
    end

296 297 298 299
    protected
      def connection(refresh = false)
        self.class.connection(refresh)
      end
300

301
      # Update the resource on the remote service.
302
      def update
303 304 305
        returning connection.put(element_path(prefix_options), to_xml) do |response|
          load_attributes_from_response(response)
        end
306
      end
307

308
      # Create (i.e., save to the remote service) the new resource.
309
      def create
310 311
        returning connection.post(collection_path, to_xml) do |response|
          self.id = id_from_response(response)
312
          load_attributes_from_response(response)
313
        end
314
      end
315 316 317 318 319 320
      
      def load_attributes_from_response(response)
        if response['Content-size'] != "0" && response.body.strip.size > 0
          load(connection.xml_from_response(response))
        end        
      end
321

322
      # Takes a response from a typical create post and pulls the ID out
323 324 325 326
      def id_from_response(response)
        response['Location'][/\/([^\/]*?)(\.\w+)?$/, 1]
      end

327 328 329 330 331 332 333 334
      def element_path(options = nil)
        self.class.element_path(id, options || prefix_options)
      end

      def collection_path(options = nil)
        self.class.collection_path(options || prefix_options)
      end

335
    private
336
      # Tries to find a resource for a given collection name; if it fails, then the resource is created
337 338 339
      def find_or_create_resource_for_collection(name)
        find_or_create_resource_for(name.to_s.singularize)
      end
340 341
      
      # Tries to find a resource for a given name; if it fails, then the resource is created
342 343
      def find_or_create_resource_for(name)
        resource_name = name.to_s.camelize
344 345 346 347 348 349 350

        # FIXME: Make it generic enough to support any depth of module nesting
        if (ancestors = self.class.name.split("::")).size > 1
          ancestors.first.constantize.const_get(resource_name)
        else
          self.class.const_get(resource_name)
        end
351 352 353
      rescue NameError
        resource = self.class.const_set(resource_name, Class.new(ActiveResource::Base))
        resource.prefix = self.class.prefix
354
        resource.site   = self.class.site
355 356 357
        resource
      end

358 359 360 361
      def split_options(options = {})
        self.class.send(:split_options, options)
      end

362
      def method_missing(method_symbol, *arguments) #:nodoc:
363
        method_name = method_symbol.to_s
364

365 366 367 368
        case method_name.last
          when "="
            attributes[method_name.first(-1)] = arguments.first
          when "?"
369
            attributes[method_name.first(-1)] == true
370
          else
371
            attributes.has_key?(method_name) ? attributes[method_name] : super
372 373 374
        end
      end
  end
J
Jeremy Kemper 已提交
375
end