base.rb 9.8 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
        self.prefix = default
45 46
        prefix(options)
      end
47

48 49
      # Sets the resource prefix
      #  prefix/collectionname/1.xml
50
      def prefix=(value = '/')
51
        # Replace :placeholders with '#{embedded options[:lookups]}'
52
        prefix_call = value.gsub(/:\w+/) { |key| "\#{options[#{key}]}" }
53 54 55

        # Redefine the new methods.
        code = <<-end_code
56 57
          def prefix_source() "#{value}" end
          def prefix(options={}) "#{prefix_call}" end
58 59
        end_code
        silence_warnings { instance_eval code, __FILE__, __LINE__ }
60
      rescue
61
        logger.error "Couldn't set prefix: #{$!}\n  #{code}"
62
        raise
63
      end
64

65
      alias_method :set_prefix, :prefix=  #:nodoc:
66

67 68
      alias_method :set_element_name, :element_name=  #:nodoc:
      alias_method :set_collection_name, :collection_name=  #:nodoc:
69 70

      def element_path(id, options = {})
71
        "#{prefix(options)}#{collection_name}/#{id}.xml#{query_string(options)}"
72
      end
73

74
      def collection_path(options = {}) 
75
        "#{prefix(options)}#{collection_name}.xml#{query_string(options)}"
76
      end
77

78
      alias_method :set_primary_key, :primary_key=  #:nodoc:
79

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
      # 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>.
      #      
      def create(attributes = {}, prefix_options = {})
        returning(self.new(attributes, prefix_options)) { |res| res.save }        
      end

95 96 97
      # Core method for finding resources.  Used similarly to ActiveRecord's find method.
      #  Person.find(1) # => GET /people/1.xml
      #  StreetAddress.find(1, :person_id => 1) # => GET /people/1/street_addresses/1.xml
98
      def find(*arguments)
99 100
        scope   = arguments.slice!(0)
        options = arguments.slice!(0) || {}
101 102

        case scope
103 104 105
          when :all   then find_every(options)
          when :first then find_every(options).first
          else             find_single(scope, options)
106 107
        end
      end
108

109 110 111 112
      def delete(id)
        connection.delete(element_path(id))
      end

113
      # Evalutes to <tt>true</tt> if the resource is found.
114 115 116 117 118 119
      def exists?(id, options = {})
        id && !find_single(id, options).nil?
      rescue ActiveResource::ResourceNotFound
        false
      end

120
      private
121
        # Find every resource.
122
        def find_every(options)
123
          collection = connection.get(collection_path(options)) || []
124
          collection.collect! { |element| new(element) }
125
        end
126

127 128
        # Find a single resource.
        #  { :person => person1 }
129
        def find_single(scope, options)
130
          new(connection.get(element_path(scope, options)), options)
131
        end
132

133
        # Accepts a URI and creates the site URI from that.
134
        def create_site_uri_from(site)
135
          site.is_a?(URI) ? site.dup : URI.parse(site)
136
        end
137

138 139 140 141
        def prefix_parameters
          @prefix_parameters ||= prefix_source.scan(/:\w+/).map { |key| key[1..-1].to_sym }.to_set
        end

142
        # Builds the query string for the request.
143 144
        def query_string(options)
          # Omit parameters which appear in the URI path.
145
          query_params = options.reject { |key, value| prefix_parameters.include?(key) }
146
          "?#{query_params.to_query}" unless query_params.empty? 
147
        end
148 149
    end

150 151
    attr_accessor :attributes #:nodoc:
    attr_accessor :prefix_options #:nodoc:
152

153
    def initialize(attributes = {}, prefix_options = {})
154
      @attributes = {}
155
      load(attributes)
156
      @prefix_options = prefix_options
157
    end
158

159
    # Is the resource a new object?
160
    def new?
161 162 163
      id.nil?
    end

164
    # Get the id of the object.
165
    def id
166
      attributes[self.class.primary_key]
167
    end
168

169
    # Set the id of the object.
170
    def id=(id)
171
      attributes[self.class.primary_key] = id
172
    end
173

174
    # 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+.
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
    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

190 191 192
    # 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).
193
    def save
194
      new? ? create : update
195 196
    end

197
    # Delete the resource.
198
    def destroy
199
      connection.delete(element_path)
200
    end
201

202
    # Evaluates to <tt>true</tt> if this resource is found.
203 204 205 206
    def exists?
      !new? && self.class.exists?(id, prefix_options)
    end

207
    # Convert the resource to an XML string
208 209
    def to_xml(options={})
      attributes.to_xml({:root => self.class.element_name}.merge(options))
210
    end
211 212 213

    # Reloads the attributes of this object from the remote web service.
    def reload
214
      self.load(self.class.find(id, @prefix_options).attributes)
215 216 217 218 219
    end

    # Manually load attributes from a hash. Recursively loads collections of
    # resources.
    def load(attributes)
J
Jeremy Kemper 已提交
220
      raise ArgumentError, "expected an attributes Hash, got #{attributes.inspect}" unless attributes.is_a?(Hash)
221 222 223 224 225 226 227
      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
228 229
              resource = find_or_create_resource_for(key)
              resource.new(value)
230
            when ActiveResource::Base
231
              value.class.new(value.attributes, value.prefix_options)
232 233 234 235
            else
              value.dup rescue value
          end
      end
236 237 238
      self
    end

239 240 241 242
    protected
      def connection(refresh = false)
        self.class.connection(refresh)
      end
243

244
      # Update the resource on the remote service.
245
      def update
246
        connection.put(element_path, to_xml)
247
      end
248

249
      # Create (i.e., save to the remote service) the new resource.
250
      def create
251 252
        returning connection.post(collection_path, to_xml) do |response|
          self.id = id_from_response(response)
253 254 255 256
          
          if response['Content-size'] != "0" && response.body.strip.size > 0
            load(connection.xml_from_response(response))
          end
257
        end
258 259
      end

260
      # Takes a response from a typical create post and pulls the ID out
261 262 263 264
      def id_from_response(response)
        response['Location'][/\/([^\/]*?)(\.\w+)?$/, 1]
      end

265 266 267 268 269 270 271 272
      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

273
    private
274
      # Tries to find a resource for a given collection name; if it fails, then the resource is created
275 276 277
      def find_or_create_resource_for_collection(name)
        find_or_create_resource_for(name.to_s.singularize)
      end
278 279
      
      # Tries to find a resource for a given name; if it fails, then the resource is created
280 281
      def find_or_create_resource_for(name)
        resource_name = name.to_s.camelize
282
        self.class.const_get(resource_name)
283 284 285
      rescue NameError
        resource = self.class.const_set(resource_name, Class.new(ActiveResource::Base))
        resource.prefix = self.class.prefix
286
        resource.site   = self.class.site
287 288 289
        resource
      end

290
      def method_missing(method_symbol, *arguments) #:nodoc:
291
        method_name = method_symbol.to_s
292

293 294 295 296
        case method_name.last
          when "="
            attributes[method_name.first(-1)] = arguments.first
          when "?"
297
            attributes[method_name.first(-1)] == true
298
          else
299
            attributes.has_key?(method_name) ? attributes[method_name] : super
300 301 302
        end
      end
  end
J
Jeremy Kemper 已提交
303
end