From aad7cac6add2fa01cebbb36e9f546292d632c9ea Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Fri, 15 Aug 2008 09:27:07 -0500 Subject: Fixed problems with the logger used if the logging string included %'s [#840 state:resolved] (Jamis Buck) --- activeresource/lib/active_resource/connection.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activeresource/lib') diff --git a/activeresource/lib/active_resource/connection.rb b/activeresource/lib/active_resource/connection.rb index 0c4ea432d7..a4a61b61b5 100644 --- a/activeresource/lib/active_resource/connection.rb +++ b/activeresource/lib/active_resource/connection.rb @@ -140,7 +140,7 @@ module ActiveResource logger.info "#{method.to_s.upcase} #{site.scheme}://#{site.host}:#{site.port}#{path}" if logger result = nil time = Benchmark.realtime { result = http.send(method, path, *arguments) } - logger.info "--> #{result.code} #{result.message} (#{result.body ? result.body.length : 0}b %.2fs)" % time if logger + logger.info "--> %d %s (%d %.2fs)" % [result.code, result.message, result.body ? result.body.length : 0, time] if logger handle_response(result) rescue Timeout::Error => e raise TimeoutError.new(e.message) -- cgit v1.2.3 From c1a8690d582c08777055caf449c03f85b4c8aa4b Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 18 Aug 2008 22:38:58 -0500 Subject: Consistently use the framework's configured logger and avoid reverting to RAILS_DEFAULT_LOGGER unless necessary. --- activeresource/lib/active_resource/connection.rb | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'activeresource/lib') diff --git a/activeresource/lib/active_resource/connection.rb b/activeresource/lib/active_resource/connection.rb index a4a61b61b5..d64fb79f1e 100644 --- a/activeresource/lib/active_resource/connection.rb +++ b/activeresource/lib/active_resource/connection.rb @@ -28,24 +28,24 @@ module ActiveResource # 3xx Redirection class Redirection < ConnectionError # :nodoc: - def to_s; response['Location'] ? "#{super} => #{response['Location']}" : super; end - end + def to_s; response['Location'] ? "#{super} => #{response['Location']}" : super; end + end # 4xx Client Error class ClientError < ConnectionError; end # :nodoc: - + # 400 Bad Request class BadRequest < ClientError; end # :nodoc - + # 401 Unauthorized class UnauthorizedAccess < ClientError; end # :nodoc - + # 403 Forbidden class ForbiddenAccess < ClientError; end # :nodoc - + # 404 Not Found class ResourceNotFound < ClientError; end # :nodoc: - + # 409 Conflict class ResourceConflict < ClientError; end # :nodoc: @@ -201,7 +201,7 @@ module ActiveResource end def logger #:nodoc: - ActiveResource::Base.logger + Base.logger end end end -- cgit v1.2.3 From 893fb5bb639b0938f6762ef1165b05abae255986 Mon Sep 17 00:00:00 2001 From: Adrian Mugnolo Date: Fri, 22 Aug 2008 03:03:26 +0100 Subject: Add ActiveResource::Base.find(:last). [#754 state:resolved] Signed-off-by: Pratik Naik --- activeresource/lib/active_resource/base.rb | 137 +++++++++++++++-------------- 1 file changed, 71 insertions(+), 66 deletions(-) (limited to 'activeresource/lib') diff --git a/activeresource/lib/active_resource/base.rb b/activeresource/lib/active_resource/base.rb index 492ab27bef..7e4a75aa70 100644 --- a/activeresource/lib/active_resource/base.rb +++ b/activeresource/lib/active_resource/base.rb @@ -13,43 +13,43 @@ module ActiveResource # to Ruby objects, Active Resource only needs a class name that corresponds to the resource name (e.g., the class # Person maps to the resources people, very similarly to Active Record) and a +site+ value, which holds the # URI of the resources. - # + # # class Person < ActiveResource::Base # self.site = "http://api.people.com:3000/" # end - # + # # Now the Person class is mapped to RESTful resources located at http://api.people.com:3000/people/, and - # you can now use Active Resource's lifecycles methods to manipulate resources. In the case where you already have + # you can now use Active Resource's lifecycles methods to manipulate resources. In the case where you already have # an existing model with the same name as the desired RESTful resource you can set the +element_name+ value. # # class PersonResource < ActiveResource::Base # self.site = "http://api.people.com:3000/" # self.element_name = "person" # end - # - # + # + # # == Lifecycle methods # # Active Resource exposes methods for creating, finding, updating, and deleting resources # from REST web services. - # + # # ryan = Person.new(:first => 'Ryan', :last => 'Daigle') # ryan.save # => true # ryan.id # => 2 # Person.exists?(ryan.id) # => true # ryan.exists? # => true - # + # # ryan = Person.find(1) # # Resource holding our newly created Person object - # + # # ryan.first = 'Rizzle' # ryan.save # => true - # + # # ryan.destroy # => true # # As you can see, these are very similar to Active Record's lifecycle methods for database records. # You can read more about each of these methods in their respective documentation. - # + # # === Custom REST methods # # Since simple CRUD/lifecycle methods can't accomplish every task, Active Resource also supports @@ -71,14 +71,14 @@ module ActiveResource # # # DELETE to 'fire' a person, i.e. DELETE /people/1/fire.xml. # Person.find(1).delete(:fire) - # + # # For more information on using custom REST methods, see the # ActiveResource::CustomMethods documentation. # # == Validations # # You can validate resources client side by overriding validation methods in the base class. - # + # # class Person < ActiveResource::Base # self.site = "http://api.people.com:3000/" # protected @@ -86,19 +86,19 @@ module ActiveResource # errors.add("last", "has invalid characters") unless last =~ /[a-zA-Z]*/ # end # end - # + # # See the ActiveResource::Validations documentation for more information. # # == Authentication - # + # # Many REST APIs will require authentication, usually in the form of basic # HTTP authentication. Authentication can be specified by: # * putting the credentials in the URL for the +site+ variable. - # + # # class Person < ActiveResource::Base # self.site = "http://ryan:password@api.people.com:3000/" # end - # + # # * defining +user+ and/or +password+ variables # # class Person < ActiveResource::Base @@ -107,29 +107,29 @@ module ActiveResource # self.password = "password" # end # - # For obvious security reasons, it is probably best if such services are available + # For obvious security reasons, it is probably best if such services are available # over HTTPS. - # - # Note: Some values cannot be provided in the URL passed to site. e.g. email addresses + # + # Note: Some values cannot be provided in the URL passed to site. e.g. email addresses # as usernames. In those situations you should use the separate user and password option. # == Errors & Validation # # Error handling and validation is handled in much the same manner as you're used to seeing in # Active Record. Both the response code in the HTTP response and the body of the response are used to # indicate that an error occurred. - # + # # === Resource errors - # + # # When a GET is requested for a resource that does not exist, the HTTP 404 (Resource Not Found) # response code will be returned from the server which will raise an ActiveResource::ResourceNotFound # exception. - # + # # # GET http://api.people.com:3000/people/999.xml # ryan = Person.find(999) # 404, raises ActiveResource::ResourceNotFound - # + # # 404 is just one of the HTTP error response codes that Active Resource will handle with its own exception. The # following HTTP response codes will also result in these exceptions: - # + # # * 200..399 - Valid response, no exception # * 404 - ActiveResource::ResourceNotFound # * 409 - ActiveResource::ResourceConflict @@ -149,17 +149,17 @@ module ActiveResource # end # # === Validation errors - # + # # Active Resource supports validations on resources and will return errors if any these validations fail - # (e.g., "First name can not be blank" and so on). These types of errors are denoted in the response by + # (e.g., "First name can not be blank" and so on). These types of errors are denoted in the response by # a response code of 422 and an XML representation of the validation errors. The save operation will # then fail (with a false return value) and the validation errors can be accessed on the resource in question. - # + # # ryan = Person.find(1) # ryan.first # => '' # ryan.save # => false # - # # When + # # When # # PUT http://api.people.com:3000/people/1.xml # # is requested with invalid values, the response is: # # @@ -169,7 +169,7 @@ module ActiveResource # # ryan.errors.invalid?(:first) # => true # ryan.errors.full_messages # => ['First cannot be empty'] - # + # # Learn more about Active Resource's validation features in the ActiveResource::Validations documentation. # # === Timeouts @@ -280,7 +280,7 @@ module ActiveResource # # Default format is :xml. def format=(mime_type_reference_or_format) - format = mime_type_reference_or_format.is_a?(Symbol) ? + format = mime_type_reference_or_format.is_a?(Symbol) ? ActiveResource::Formats[mime_type_reference_or_format] : mime_type_reference_or_format write_inheritable_attribute("format", format) @@ -332,7 +332,7 @@ module ActiveResource attr_accessor_with_default(:collection_name) { element_name.pluralize } #:nodoc: attr_accessor_with_default(:primary_key, 'id') #:nodoc: - + # Gets the prefix for a resource's nested URL (e.g., prefix/collectionname/1.xml) # This method is regenerated at runtime based on what the prefix is set to. def prefix(options={}) @@ -381,21 +381,21 @@ module ActiveResource # +query_options+ - A hash to add items to the query string for the request. # # ==== Examples - # Post.element_path(1) + # Post.element_path(1) # # => /posts/1.xml # - # Comment.element_path(1, :post_id => 5) + # Comment.element_path(1, :post_id => 5) # # => /posts/5/comments/1.xml # - # Comment.element_path(1, :post_id => 5, :active => 1) + # 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}) + # 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}.#{format.extension}#{query_string(query_options)}" + "#{prefix(prefix_options)}#{collection_name}/#{id}.#{format.extension}#{query_string(query_options)}" end # Gets the collection path for the REST resources. If the +query_options+ parameter is omitted, Rails @@ -410,13 +410,13 @@ module ActiveResource # Post.collection_path # # => /posts.xml # - # Comment.collection_path(:post_id => 5) + # Comment.collection_path(:post_id => 5) # # => /posts/5/comments.xml # - # Comment.collection_path(:post_id => 5, :active => 1) + # Comment.collection_path(:post_id => 5, :active => 1) # # => /posts/5/comments.xml?active=1 # - # Comment.collection_path({:post_id => 5}, {:active => 1}) + # Comment.collection_path({:post_id => 5}, {:active => 1}) # # => /posts/5/comments.xml?active=1 # def collection_path(prefix_options = {}, query_options = nil) @@ -451,50 +451,54 @@ module ActiveResource # that_guy.valid? # => false # that_guy.new? # => true def create(attributes = {}) - returning(self.new(attributes)) { |res| res.save } + returning(self.new(attributes)) { |res| res.save } end # Core method for finding resources. Used similarly to Active Record's +find+ method. # # ==== Arguments - # The first argument is considered to be the scope of the query. That is, how many + # The first argument is considered to be the scope of the query. That is, how many # resources are returned from the request. It can be one of the following. # # * :one - Returns a single resource. # * :first - Returns the first resource found. + # * :last - Returns the last resource found. # * :all - Returns every resource that matches the request. - # + # # ==== Options # # * :from - Sets the path or custom method that resources will be fetched from. # * :params - Sets query and prefix (nested URL) parameters. # # ==== Examples - # Person.find(1) + # Person.find(1) # # => GET /people/1.xml # - # Person.find(:all) + # Person.find(:all) # # => GET /people.xml # - # Person.find(:all, :params => { :title => "CEO" }) + # Person.find(:all, :params => { :title => "CEO" }) # # => GET /people.xml?title=CEO # - # Person.find(:first, :from => :managers) + # Person.find(:first, :from => :managers) + # # => GET /people/managers.xml + # + # Person.find(:last, :from => :managers) # # => GET /people/managers.xml # - # Person.find(:all, :from => "/companies/1/people.xml") + # Person.find(:all, :from => "/companies/1/people.xml") # # => GET /companies/1/people.xml # - # Person.find(:one, :from => :leader) + # Person.find(:one, :from => :leader) # # => GET /people/leader.xml # # Person.find(:all, :from => :developers, :params => { :language => 'ruby' }) # # => GET /people/developers.xml?language=ruby # - # Person.find(:one, :from => "/companies/1/manager.xml") + # Person.find(:one, :from => "/companies/1/manager.xml") # # => GET /companies/1/manager.xml # - # StreetAddress.find(1, :params => { :person_id => 1 }) + # StreetAddress.find(1, :params => { :person_id => 1 }) # # => GET /people/1/street_addresses/1.xml def find(*arguments) scope = arguments.slice!(0) @@ -503,6 +507,7 @@ module ActiveResource case scope when :all then find_every(options) when :first then find_every(options).first + when :last then find_every(options).last when :one then find_one(options) else find_single(scope, options) end @@ -560,7 +565,7 @@ module ActiveResource instantiate_collection( (connection.get(path, headers) || []), prefix_options ) end end - + # Find a single resource from a one-off URL def find_one(options) case from = options[:from] @@ -578,7 +583,7 @@ module ActiveResource path = element_path(scope, prefix_options, query_options) instantiate_record(connection.get(path, headers), prefix_options) end - + def instantiate_collection(collection, prefix_options = {}) collection.collect! { |record| instantiate_record(record, prefix_options) } end @@ -602,10 +607,10 @@ module ActiveResource # Builds the query string for the request. def query_string(options) - "?#{options.to_query}" unless options.nil? || options.empty? + "?#{options.to_query}" unless options.nil? || options.empty? end - # split an option hash into two hashes, one containing the prefix options, + # 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 = {}, {} @@ -654,7 +659,7 @@ module ActiveResource # ryan = Person.find(1) # ryan.address = StreetAddress.find(1, :person_id => ryan.id) # ryan.hash = {:not => "an ARes instance"} - # + # # not_ryan = ryan.clone # not_ryan.new? # => true # not_ryan.address # => NoMethodError @@ -706,7 +711,7 @@ module ActiveResource id && id.to_s end - # Test for equality. Resource are equal if and only if +other+ is the same object or + # Test for equality. Resource are equal 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+. # # ==== Examples @@ -742,7 +747,7 @@ module ActiveResource def hash id.hash end - + # Duplicate the current resource without saving it. # # ==== Examples @@ -762,7 +767,7 @@ module ActiveResource end end - # A method to save (+POST+) or update (+PUT+) a resource. It delegates to +create+ if a new object, + # A method to save (+POST+) or update (+PUT+) a resource. It delegates to +create+ if a new object, # +update+ if it is existing. 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 weren't part of the original submit). @@ -786,7 +791,7 @@ module ActiveResource # my_person = Person.find(my_id) # my_person.destroy # Person.find(my_id) # 404 (Resource Not Found) - # + # # new_person = Person.create(:name => 'James') # new_id = new_person.id # => 7 # new_person.destroy @@ -825,7 +830,7 @@ module ActiveResource # * :indent - Set the indent level for the XML output (default is +2+). # * :dasherize - Boolean option to determine whether or not element names should # replace underscores with dashes (default is false). - # * :skip_instruct - Toggle skipping the +instruct!+ call on the XML builder + # * :skip_instruct - Toggle skipping the +instruct!+ call on the XML builder # that generates the XML declaration (default is false). # # ==== Examples @@ -849,7 +854,7 @@ module ActiveResource # ==== Examples # my_branch = Branch.find(:first) # my_branch.name # => "Wislon Raod" - # + # # # Another client fixes the typo... # # my_branch.name # => "Wislon Raod" @@ -897,7 +902,7 @@ module ActiveResource end self end - + # For checking respond_to? without searching the attributes (which is faster). alias_method :respond_to_without_attributes?, :respond_to? @@ -909,7 +914,7 @@ module ActiveResource if attributes.nil? return super elsif attributes.has_key?(method_name) - return true + return true elsif ['?','='].include?(method_name.last) && attributes.has_key?(method_name.first(-1)) return true end @@ -917,7 +922,7 @@ module ActiveResource # would return true for generated readers, even if the attribute wasn't present super end - + protected def connection(refresh = false) @@ -938,7 +943,7 @@ module ActiveResource load_attributes_from_response(response) end end - + def load_attributes_from_response(response) if response['Content-Length'] != "0" && response.body.strip.size > 0 load(self.class.format.decode(response.body)) @@ -963,7 +968,7 @@ module ActiveResource def find_or_create_resource_for_collection(name) find_or_create_resource_for(name.to_s.singularize) end - + # Tries to find a resource in a non empty list of nested modules # Raises a NameError if it was not found in any of the given nested modules def find_resource_in_modules(resource_name, module_names) -- cgit v1.2.3 From b5c4c7daf8e26e829ec4d7ece91f622d9e1a49fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tarmo=20T=C3=A4nav?= Date: Sat, 23 Aug 2008 17:40:16 +0300 Subject: Clear prefix_parameters cache when setting prefix --- activeresource/lib/active_resource/base.rb | 3 +++ 1 file changed, 3 insertions(+) (limited to 'activeresource/lib') diff --git a/activeresource/lib/active_resource/base.rb b/activeresource/lib/active_resource/base.rb index 7e4a75aa70..4af30ea13f 100644 --- a/activeresource/lib/active_resource/base.rb +++ b/activeresource/lib/active_resource/base.rb @@ -356,6 +356,9 @@ module ActiveResource # Replace :placeholders with '#{embedded options[:lookups]}' prefix_call = value.gsub(/:\w+/) { |key| "\#{options[#{key}]}" } + # Clear prefix parameters in case they have been cached + @prefix_parameters = nil + # Redefine the new methods. code = <<-end_code def prefix_source() "#{value}" end -- cgit v1.2.3 From 172606e21f54fea39af68ede5f55a43deaf3ac68 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 25 Aug 2008 21:22:34 -0700 Subject: Harmonize framework require strategy. Don't add self to load path since Rails initializer and RubyGems handle it. --- activeresource/lib/active_resource.rb | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) (limited to 'activeresource/lib') diff --git a/activeresource/lib/active_resource.rb b/activeresource/lib/active_resource.rb index 18347457aa..db9007060f 100644 --- a/activeresource/lib/active_resource.rb +++ b/activeresource/lib/active_resource.rb @@ -21,16 +21,13 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #++ -$:.unshift(File.dirname(__FILE__)) unless - $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) - -unless defined?(ActiveSupport) - begin - $:.unshift(File.dirname(__FILE__) + "/../../activesupport/lib") +begin + require 'active_support' +rescue LoadError + activesupport_path = "#{File.dirname(__FILE__)}/../../activesupport/lib" + if File.directory?(activesupport_path) + $:.unshift activesupport_path require 'active_support' - rescue LoadError - require 'rubygems' - gem 'activesupport' end end @@ -44,4 +41,4 @@ module ActiveResource include Validations include CustomMethods end -end \ No newline at end of file +end -- cgit v1.2.3 From 16b9a554db7e1bf3f5f224cdc5b4d27480e053ff Mon Sep 17 00:00:00 2001 From: Rasik Pandey Date: Sat, 30 Aug 2008 04:19:18 +0300 Subject: Format related patches to support serializing data out in the correct format with correct http request headers per http method type [#450 state:resolved] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Tarmo Tänav Signed-off-by: Jeremy Kemper --- activeresource/lib/active_resource/base.rb | 13 +++++++---- activeresource/lib/active_resource/connection.rb | 25 ++++++++++++++++------ .../lib/active_resource/custom_methods.rb | 19 ++++++++-------- .../lib/active_resource/formats/json_format.rb | 12 +++++------ .../lib/active_resource/formats/xml_format.rb | 18 ++++++++-------- activeresource/lib/active_resource/http_mock.rb | 2 +- 6 files changed, 53 insertions(+), 36 deletions(-) (limited to 'activeresource/lib') diff --git a/activeresource/lib/active_resource/base.rb b/activeresource/lib/active_resource/base.rb index 4af30ea13f..fb23b13fbb 100644 --- a/activeresource/lib/active_resource/base.rb +++ b/activeresource/lib/active_resource/base.rb @@ -848,8 +848,13 @@ module ActiveResource # # my_group.to_xml(:skip_instruct => true) # # => [...] - def to_xml(options={}) - attributes.to_xml({:root => self.class.element_name}.merge(options)) + def encode(options={}) + case self.class.format + when ActiveResource::Formats[:xml] + self.class.format.encode(attributes, {:root => self.class.element_name}.merge(options)) + else + self.class.format.encode(attributes, options) + end end # A method to reload the attributes of this object from the remote web service. @@ -934,14 +939,14 @@ module ActiveResource # Update the resource on the remote service. def update - returning connection.put(element_path(prefix_options), to_xml, self.class.headers) do |response| + returning connection.put(element_path(prefix_options), encode, self.class.headers) do |response| load_attributes_from_response(response) end end # Create (i.e., save to the remote service) the new resource. def create - returning connection.post(collection_path, to_xml, self.class.headers) do |response| + returning connection.post(collection_path, encode, self.class.headers) do |response| self.id = id_from_response(response) load_attributes_from_response(response) end diff --git a/activeresource/lib/active_resource/connection.rb b/activeresource/lib/active_resource/connection.rb index d64fb79f1e..fe9c2d57fe 100644 --- a/activeresource/lib/active_resource/connection.rb +++ b/activeresource/lib/active_resource/connection.rb @@ -63,6 +63,13 @@ module ActiveResource # This class is used by ActiveResource::Base to interface with REST # services. class Connection + + HTTP_FORMAT_HEADER_NAMES = { :get => 'Accept', + :put => 'Content-Type', + :post => 'Content-Type', + :delete => 'Accept' + } + attr_reader :site, :user, :password, :timeout attr_accessor :format @@ -106,25 +113,25 @@ module ActiveResource # Execute a GET request. # Used to get (find) resources. def get(path, headers = {}) - format.decode(request(:get, path, build_request_headers(headers)).body) + format.decode(request(:get, path, build_request_headers(headers, :get)).body) end # Execute a DELETE request (see HTTP protocol documentation if unfamiliar). # Used to delete resources. def delete(path, headers = {}) - request(:delete, path, build_request_headers(headers)) + request(:delete, path, build_request_headers(headers, :delete)) end # Execute a PUT request (see HTTP protocol documentation if unfamiliar). # Used to update resources. def put(path, body = '', headers = {}) - request(:put, path, body.to_s, build_request_headers(headers)) + request(:put, path, body.to_s, build_request_headers(headers, :put)) end # Execute a POST request. # Used to create new resources. def post(path, body = '', headers = {}) - request(:post, path, body.to_s, build_request_headers(headers)) + request(:post, path, body.to_s, build_request_headers(headers, :post)) end # Execute a HEAD request. @@ -187,12 +194,12 @@ module ActiveResource end def default_header - @default_header ||= { 'Content-Type' => format.mime_type } + @default_header ||= {} end # Builds headers for request to remote service. - def build_request_headers(headers) - authorization_header.update(default_header).update(headers) + def build_request_headers(headers, http_method=nil) + authorization_header.update(default_header).update(headers).update(http_format_header(http_method)) end # Sets authorization header @@ -200,6 +207,10 @@ module ActiveResource (@user || @password ? { 'Authorization' => 'Basic ' + ["#{@user}:#{ @password}"].pack('m').delete("\r\n") } : {}) end + def http_format_header(http_method) + {HTTP_FORMAT_HEADER_NAMES[http_method] => format.mime_type} + end + def logger #:nodoc: Base.logger end diff --git a/activeresource/lib/active_resource/custom_methods.rb b/activeresource/lib/active_resource/custom_methods.rb index 770116ceb7..b6fffc4da2 100644 --- a/activeresource/lib/active_resource/custom_methods.rb +++ b/activeresource/lib/active_resource/custom_methods.rb @@ -30,7 +30,7 @@ module ActiveResource # Person.get(:active) # GET /people/active.xml # # => [{:id => 1, :name => 'Ryan'}, {:id => 2, :name => 'Joe'}] # - module CustomMethods + module CustomMethods def self.included(base) base.class_eval do extend ActiveResource::CustomMethods::ClassMethods @@ -83,24 +83,25 @@ module ActiveResource "#{prefix(prefix_options)}#{collection_name}/#{method_name}.#{format.extension}#{query_string(query_options)}" end end - + module InstanceMethods def get(method_name, options = {}) connection.get(custom_method_element_url(method_name, options), self.class.headers) end - - def post(method_name, options = {}, body = '') + + def post(method_name, options = {}, body = nil) + request_body = body.nil? ? encode : body if new? - connection.post(custom_method_new_element_url(method_name, options), (body.nil? ? to_xml : body), self.class.headers) + connection.post(custom_method_new_element_url(method_name, options), request_body, self.class.headers) else - connection.post(custom_method_element_url(method_name, options), body, self.class.headers) + connection.post(custom_method_element_url(method_name, options), request_body, self.class.headers) end end - + def put(method_name, options = {}, body = '') connection.put(custom_method_element_url(method_name, options), body, self.class.headers) end - + def delete(method_name, options = {}) connection.delete(custom_method_element_url(method_name, options), self.class.headers) end @@ -110,7 +111,7 @@ module ActiveResource def custom_method_element_url(method_name, options = {}) "#{self.class.prefix(prefix_options)}#{self.class.collection_name}/#{id}/#{method_name}.#{self.class.format.extension}#{self.class.send!(:query_string, options)}" end - + def custom_method_new_element_url(method_name, options = {}) "#{self.class.prefix(prefix_options)}#{self.class.collection_name}/new/#{method_name}.#{self.class.format.extension}#{self.class.send!(:query_string, options)}" end diff --git a/activeresource/lib/active_resource/formats/json_format.rb b/activeresource/lib/active_resource/formats/json_format.rb index df0d6ca372..9e269d4ded 100644 --- a/activeresource/lib/active_resource/formats/json_format.rb +++ b/activeresource/lib/active_resource/formats/json_format.rb @@ -2,22 +2,22 @@ module ActiveResource module Formats module JsonFormat extend self - + def extension "json" end - + def mime_type "application/json" end - - def encode(hash) + + def encode(hash, options={}) hash.to_json end - + def decode(json) ActiveSupport::JSON.decode(json) end end end -end \ No newline at end of file +end diff --git a/activeresource/lib/active_resource/formats/xml_format.rb b/activeresource/lib/active_resource/formats/xml_format.rb index 5e97ffa776..86c6cec745 100644 --- a/activeresource/lib/active_resource/formats/xml_format.rb +++ b/activeresource/lib/active_resource/formats/xml_format.rb @@ -2,23 +2,23 @@ module ActiveResource module Formats module XmlFormat extend self - + def extension "xml" end - + def mime_type "application/xml" end - - def encode(hash) - hash.to_xml + + def encode(hash, options={}) + hash.to_xml(options) end - + def decode(xml) from_xml_data(Hash.from_xml(xml)) end - + private # Manipulate from_xml Hash, because xml_simple is not exactly what we # want for Active Resource. @@ -28,7 +28,7 @@ module ActiveResource else data end - end + end end end -end \ No newline at end of file +end diff --git a/activeresource/lib/active_resource/http_mock.rb b/activeresource/lib/active_resource/http_mock.rb index 554fc3bcfc..9ed532b48c 100644 --- a/activeresource/lib/active_resource/http_mock.rb +++ b/activeresource/lib/active_resource/http_mock.rb @@ -146,7 +146,7 @@ module ActiveResource attr_accessor :path, :method, :body, :headers def initialize(method, path, body = nil, headers = {}) - @method, @path, @body, @headers = method, path, body, headers.reverse_merge('Content-Type' => 'application/xml') + @method, @path, @body, @headers = method, path, body, headers.merge(ActiveResource::Connection::HTTP_FORMAT_HEADER_NAMES[method] => 'application/xml') end def ==(other_request) -- cgit v1.2.3 From a1eb4e11c2cccb91483fa15f1a1a0b2ae518d2cf Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 31 Aug 2008 13:15:26 -0700 Subject: Get rid of 'Object#send!'. It was originally added because it's in Ruby 1.9, but it has since been removed from 1.9. Signed-off-by: Jeremy Kemper Conflicts: actionpack/test/controller/layout_test.rb --- activeresource/lib/active_resource/base.rb | 2 +- activeresource/lib/active_resource/custom_methods.rb | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'activeresource/lib') diff --git a/activeresource/lib/active_resource/base.rb b/activeresource/lib/active_resource/base.rb index fb23b13fbb..9dc715b0fa 100644 --- a/activeresource/lib/active_resource/base.rb +++ b/activeresource/lib/active_resource/base.rb @@ -1012,7 +1012,7 @@ module ActiveResource end def split_options(options = {}) - self.class.send!(:split_options, options) + self.class.__send__(:split_options, options) end def method_missing(method_symbol, *arguments) #:nodoc: diff --git a/activeresource/lib/active_resource/custom_methods.rb b/activeresource/lib/active_resource/custom_methods.rb index b6fffc4da2..24306f251d 100644 --- a/activeresource/lib/active_resource/custom_methods.rb +++ b/activeresource/lib/active_resource/custom_methods.rb @@ -109,11 +109,11 @@ module ActiveResource private def custom_method_element_url(method_name, options = {}) - "#{self.class.prefix(prefix_options)}#{self.class.collection_name}/#{id}/#{method_name}.#{self.class.format.extension}#{self.class.send!(:query_string, options)}" + "#{self.class.prefix(prefix_options)}#{self.class.collection_name}/#{id}/#{method_name}.#{self.class.format.extension}#{self.class.__send__(:query_string, options)}" end def custom_method_new_element_url(method_name, options = {}) - "#{self.class.prefix(prefix_options)}#{self.class.collection_name}/new/#{method_name}.#{self.class.format.extension}#{self.class.send!(:query_string, options)}" + "#{self.class.prefix(prefix_options)}#{self.class.collection_name}/new/#{method_name}.#{self.class.format.extension}#{self.class.__send__(:query_string, options)}" end end end -- cgit v1.2.3 From 1646e8c36495680756304b23b7301dbda9cad07a Mon Sep 17 00:00:00 2001 From: Clemens Kofler Date: Tue, 2 Sep 2008 10:04:53 +0200 Subject: More symbols for send and respond_to?. Signed-off-by: Jeremy Kemper --- activeresource/lib/active_resource/base.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'activeresource/lib') diff --git a/activeresource/lib/active_resource/base.rb b/activeresource/lib/active_resource/base.rb index 9dc715b0fa..da9f6d6893 100644 --- a/activeresource/lib/active_resource/base.rb +++ b/activeresource/lib/active_resource/base.rb @@ -915,8 +915,8 @@ module ActiveResource alias_method :respond_to_without_attributes?, :respond_to? # A method to determine if an object responds to a message (e.g., a method call). In Active Resource, a Person object with a - # +name+ attribute can answer true to my_person.respond_to?("name"), my_person.respond_to?("name="), and - # my_person.respond_to?("name?"). + # +name+ attribute can answer true to my_person.respond_to?(:name), my_person.respond_to?(:name=), and + # my_person.respond_to?(:name?). def respond_to?(method, include_priv = false) method_name = method.to_s if attributes.nil? -- cgit v1.2.3 From 288e947ae1737645985fde76f5382baaff700505 Mon Sep 17 00:00:00 2001 From: Clemens Kofler Date: Tue, 2 Sep 2008 15:33:49 +0200 Subject: Some performance goodness for inheritable attributes. Signed-off-by: Jeremy Kemper --- activeresource/lib/active_resource/base.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'activeresource/lib') diff --git a/activeresource/lib/active_resource/base.rb b/activeresource/lib/active_resource/base.rb index da9f6d6893..749cc59284 100644 --- a/activeresource/lib/active_resource/base.rb +++ b/activeresource/lib/active_resource/base.rb @@ -283,13 +283,13 @@ module ActiveResource format = mime_type_reference_or_format.is_a?(Symbol) ? ActiveResource::Formats[mime_type_reference_or_format] : mime_type_reference_or_format - write_inheritable_attribute("format", format) + write_inheritable_attribute(:format, format) connection.format = format if site end # Returns the current format, default is ActiveResource::Formats::XmlFormat. def format - read_inheritable_attribute("format") || ActiveResource::Formats[:xml] + read_inheritable_attribute(:format) || ActiveResource::Formats[:xml] end # Sets the number of seconds after which requests to the REST API should time out. -- cgit v1.2.3