Rails 2.1.1

Among other things, a security fix.
This commit is contained in:
Jacques Distler 2008-09-07 00:54:05 -05:00
parent d2c4c8737c
commit d4f97345db
354 changed files with 21027 additions and 3072 deletions

View file

@ -1,3 +1,8 @@
*2.1.1 (September 4th, 2008)*
* Fixed Base#exists? to check status code as integer [#299 state:resolved] (Wes Oldenbeuving)
*2.1.0 (May 31st, 2008)*
* Fixed response logging to use length instead of the entire thing (seangeo) [#27]

View file

@ -5,6 +5,7 @@ require 'rake/rdoctask'
require 'rake/packagetask'
require 'rake/gempackagetask'
require 'rake/contrib/sshpublisher'
require 'rake/contrib/rubyforgepublisher'
require File.join(File.dirname(__FILE__), 'lib', 'active_resource', 'version')
@ -42,9 +43,10 @@ Rake::RDocTask.new { |rdoc|
rdoc.title = "Active Resource -- Object-oriented REST services"
rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object'
rdoc.options << '--charset' << 'utf-8'
rdoc.template = "#{ENV['template']}.rb" if ENV['template']
rdoc.template = ENV['template'] ? "#{ENV['template']}.rb" : '../doc/template/horo'
rdoc.rdoc_files.include('README', 'CHANGELOG')
rdoc.rdoc_files.include('lib/**/*.rb')
rdoc.rdoc_files.exclude('lib/activeresource.rb')
}
@ -64,7 +66,7 @@ spec = Gem::Specification.new do |s|
s.files = s.files + Dir.glob( "#{dir}/**/*" ).delete_if { |item| item.include?( "\.svn" ) }
end
s.add_dependency('activesupport', '= 2.1.0' + PKG_BUILD)
s.add_dependency('activesupport', '= 2.1.1' + PKG_BUILD)
s.require_path = 'lib'
s.autorequire = 'active_resource'
@ -114,13 +116,13 @@ end
desc "Publish the beta gem"
task :pgem => [:package] do
Rake::SshFilePublisher.new("davidhh@wrath.rubyonrails.org", "public_html/gems/gems", "pkg", "#{PKG_FILE_NAME}.gem").upload
`ssh davidhh@wrath.rubyonrails.org './gemupdate.sh'`
Rake::SshFilePublisher.new("david@greed.loudthinking.com", "/u/sites/gems/gems", "pkg", "#{PKG_FILE_NAME}.gem").upload
`ssh david@greed.loudthinking.com '/u/sites/gems/gemupdate.sh'`
end
desc "Publish the API documentation"
task :pdoc => [:rdoc] do
Rake::SshDirPublisher.new("davidhh@wrath.rubyonrails.org", "public_html/ar", "doc").upload
Rake::SshDirPublisher.new("wrath.rubyonrails.org", "public_html/ar", "doc").upload
end
desc "Publish the release files to RubyForge."

View file

@ -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
@ -538,7 +541,7 @@ module ActiveResource
prefix_options, query_options = split_options(options[:params])
path = element_path(id, prefix_options, query_options)
response = connection.head(path, headers)
response.code == 200
response.code.to_i == 200
end
# id && !find_single(id, options).nil?
rescue ActiveResource::ResourceNotFound
@ -840,8 +843,13 @@ module ActiveResource
#
# my_group.to_xml(:skip_instruct => true)
# # => <subsidiary_group> [...] </subsidiary_group>
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.
@ -926,14 +934,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
@ -988,7 +996,11 @@ module ActiveResource
self.class.const_get(resource_name)
end
rescue NameError
resource = self.class.const_set(resource_name, Class.new(ActiveResource::Base))
if self.class.const_defined?(resource_name)
resource = self.class.const_get(resource_name)
else
resource = self.class.const_set(resource_name, Class.new(ActiveResource::Base))
end
resource.prefix = self.class.prefix
resource.site = self.class.site
resource

View file

@ -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:
ActiveResource::Base.logger
end

View file

@ -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

View file

@ -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
end

View file

@ -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
end

View file

@ -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)

View file

@ -2,7 +2,7 @@ module ActiveResource
module VERSION #:nodoc:
MAJOR = 2
MINOR = 1
TINY = 0
TINY = 1
STRING = [MAJOR, MINOR, TINY].join('.')
end

View file

@ -9,14 +9,18 @@ require 'setter_trap'
ActiveResource::Base.logger = Logger.new("#{File.dirname(__FILE__)}/debug.log")
# Wrap tests that use Mocha and skip if unavailable.
def uses_mocha(test_name)
unless Object.const_defined?(:Mocha)
require 'mocha'
require 'stubba'
end
def uses_gem(gem_name, test_name, version = '> 0')
require 'rubygems'
gem gem_name.to_s, version
require gem_name.to_s
yield
rescue LoadError => load_error
raise unless load_error.message =~ /mocha/i
$stderr.puts "Skipping #{test_name} tests. `gem install mocha` and try again."
end
rescue LoadError
$stderr.puts "Skipping #{test_name} tests. `gem install #{gem_name}` and try again."
end
# Wrap tests that use Mocha and skip if unavailable.
unless defined? uses_mocha
def uses_mocha(test_name, &block)
uses_gem('mocha', test_name, '>= 0.5.5', &block)
end
end

View file

@ -10,8 +10,7 @@ class CustomMethodsTest < Test::Unit::TestCase
@ryan = { :name => 'Ryan' }.to_xml(:root => 'person')
@addy = { :id => 1, :street => '12345 Street' }.to_xml(:root => 'address')
@addy_deep = { :id => 1, :street => '12345 Street', :zip => "27519" }.to_xml(:root => 'address')
@default_request_headers = { 'Content-Type' => 'application/xml' }
ActiveResource::HttpMock.respond_to do |mock|
mock.get "/people/1.xml", {}, @matz
mock.get "/people/1/shallow.xml", {}, @matz

View file

@ -1,5 +1,6 @@
require 'abstract_unit'
require "fixtures/person"
require "fixtures/customer"
require "fixtures/street_address"
require "fixtures/beast"
@ -15,6 +16,37 @@ class BaseTest < Test::Unit::TestCase
@people_david = [{ :id => 2, :name => 'David' }].to_xml(:root => 'people')
@addresses = [{ :id => 1, :street => '12345 Street' }].to_xml(:root => 'addresses')
# - deep nested resource -
# - Luis (Customer)
# - JK (Customer::Friend)
# - Mateo (Customer::Friend::Brother)
# - Edith (Customer::Friend::Brother::Child)
# - Martha (Customer::Friend::Brother::Child)
# - Felipe (Customer::Friend::Brother)
# - Bryan (Customer::Friend::Brother::Child)
# - Luke (Customer::Friend::Brother::Child)
# - Eduardo (Customer::Friend)
# - Sebas (Customer::Friend::Brother)
# - Andres (Customer::Friend::Brother::Child)
# - Jorge (Customer::Friend::Brother::Child)
# - Elsa (Customer::Friend::Brother)
# - Natacha (Customer::Friend::Brother::Child)
# - Milena (Customer::Friend::Brother)
#
@luis = {:id => 1, :name => 'Luis',
:friends => [{:name => 'JK',
:brothers => [{:name => 'Mateo',
:children => [{:name => 'Edith'},{:name => 'Martha'}]},
{:name => 'Felipe',
:children => [{:name => 'Bryan'},{:name => 'Luke'}]}]},
{:name => 'Eduardo',
:brothers => [{:name => 'Sebas',
:children => [{:name => 'Andres'},{:name => 'Jorge'}]},
{:name => 'Elsa',
:children => [{:name => 'Natacha'}]},
{:name => 'Milena',
:children => []}]}]}.to_xml(:root => 'customer')
ActiveResource::HttpMock.respond_to do |mock|
mock.get "/people/1.xml", {}, @matz
mock.get "/people/2.xml", {}, @david
@ -46,6 +78,8 @@ class BaseTest < Test::Unit::TestCase
mock.head "/people/1/addresses/2.xml", {}, nil, 404
mock.head "/people/2/addresses/1.xml", {}, nil, 404
mock.head "/people/Greg/addresses/1.xml", {}, nil, 200
# customer
mock.get "/customers/1.xml", {}, @luis
end
Person.user = nil
@ -450,7 +484,16 @@ class BaseTest < Test::Unit::TestCase
assert_equal "the_prefixthe_param_value", person_class.prefix(:the_param => "the_param_value")
end
end
def test_set_prefix_twice_should_clear_params
SetterTrap.rollback_sets(Person) do |person_class|
person_class.prefix = "the_prefix/:the_param1"
assert_equal Set.new([:the_param1]), person_class.prefix_parameters
person_class.prefix = "the_prefix/:the_param2"
assert_equal Set.new([:the_param2]), person_class.prefix_parameters
end
end
def test_set_prefix_with_default_value
SetterTrap.rollback_sets(Person) do |person_class|
person_class.set_prefix
@ -776,7 +819,7 @@ class BaseTest < Test::Unit::TestCase
def test_to_xml
matz = Person.find(1)
xml = matz.to_xml
xml = matz.encode
assert xml.starts_with?('<?xml version="1.0" encoding="UTF-8"?>')
assert xml.include?('<name>Matz</name>')
assert xml.include?('<id type="integer">1</id>')
@ -788,4 +831,18 @@ class BaseTest < Test::Unit::TestCase
matz = Person.find(1)
assert_equal '1', matz.to_param
end
def test_parse_deep_nested_resources
luis = Customer.find(1)
assert_kind_of Customer, luis
luis.friends.each do |friend|
assert_kind_of Customer::Friend, friend
friend.brothers.each do |brother|
assert_kind_of Customer::Friend::Brother, brother
brother.children.each do |child|
assert_kind_of Customer::Friend::Brother::Child, child
end
end
end
end
end

View file

@ -0,0 +1,3 @@
class Customer < ActiveResource::Base
self.site = "http://37s.sunrise.i:3000"
end

View file

@ -5,14 +5,22 @@ class FormatTest < Test::Unit::TestCase
def setup
@matz = { :id => 1, :name => 'Matz' }
@david = { :id => 2, :name => 'David' }
@programmers = [ @matz, @david ]
end
def test_http_format_header_name
header_name = ActiveResource::Connection::HTTP_FORMAT_HEADER_NAMES[:get]
assert_equal 'Accept', header_name
headers_names = [ActiveResource::Connection::HTTP_FORMAT_HEADER_NAMES[:put], ActiveResource::Connection::HTTP_FORMAT_HEADER_NAMES[:post]]
headers_names.each{|header_name| assert_equal 'Content-Type', header_name}
end
def test_formats_on_single_element
for format in [ :json, :xml ]
using_format(Person, format) do
ActiveResource::HttpMock.respond_to.get "/people/1.#{format}", {}, ActiveResource::Formats[format].encode(@david)
ActiveResource::HttpMock.respond_to.get "/people/1.#{format}", {'Accept' => ActiveResource::Formats[format].mime_type}, ActiveResource::Formats[format].encode(@david)
assert_equal @david[:name], Person.find(1).name
end
end
@ -21,7 +29,7 @@ class FormatTest < Test::Unit::TestCase
def test_formats_on_collection
for format in [ :json, :xml ]
using_format(Person, format) do
ActiveResource::HttpMock.respond_to.get "/people.#{format}", {}, ActiveResource::Formats[format].encode(@programmers)
ActiveResource::HttpMock.respond_to.get "/people.#{format}", {'Accept' => ActiveResource::Formats[format].mime_type}, ActiveResource::Formats[format].encode(@programmers)
remote_programmers = Person.find(:all)
assert_equal 2, remote_programmers.size
assert remote_programmers.select { |p| p.name == 'David' }
@ -32,7 +40,7 @@ class FormatTest < Test::Unit::TestCase
def test_formats_on_custom_collection_method
for format in [ :json, :xml ]
using_format(Person, format) do
ActiveResource::HttpMock.respond_to.get "/people/retrieve.#{format}?name=David", {}, ActiveResource::Formats[format].encode([@david])
ActiveResource::HttpMock.respond_to.get "/people/retrieve.#{format}?name=David", {'Accept' => ActiveResource::Formats[format].mime_type}, ActiveResource::Formats[format].encode([@david])
remote_programmers = Person.get(:retrieve, :name => 'David')
assert_equal 1, remote_programmers.size
assert_equal @david[:id], remote_programmers[0]['id']
@ -40,13 +48,13 @@ class FormatTest < Test::Unit::TestCase
end
end
end
def test_formats_on_custom_element_method
for format in [ :json, :xml ]
using_format(Person, format) do
ActiveResource::HttpMock.respond_to do |mock|
mock.get "/people/2.#{format}", {}, ActiveResource::Formats[format].encode(@david)
mock.get "/people/2/shallow.#{format}", {}, ActiveResource::Formats[format].encode(@david)
mock.get "/people/2.#{format}", {'Accept' => ActiveResource::Formats[format].mime_type}, ActiveResource::Formats[format].encode(@david)
mock.get "/people/2/shallow.#{format}", {'Accept' => ActiveResource::Formats[format].mime_type}, ActiveResource::Formats[format].encode(@david)
end
remote_programmer = Person.find(2).get(:shallow)
assert_equal @david[:id], remote_programmer['id']
@ -57,20 +65,24 @@ class FormatTest < Test::Unit::TestCase
for format in [ :json, :xml ]
ryan = ActiveResource::Formats[format].encode({ :name => 'Ryan' })
using_format(Person, format) do
ActiveResource::HttpMock.respond_to.post "/people/new/register.#{format}", {}, ryan, 201, 'Location' => "/people/5.#{format}"
remote_ryan = Person.new(:name => 'Ryan')
ActiveResource::HttpMock.respond_to.post "/people.#{format}", {'Content-Type' => ActiveResource::Formats[format].mime_type}, ryan, 201, {'Location' => "/people/5.#{format}"}
remote_ryan.save
remote_ryan = Person.new(:name => 'Ryan')
ActiveResource::HttpMock.respond_to.post "/people/new/register.#{format}", {'Content-Type' => ActiveResource::Formats[format].mime_type}, ryan, 201, {'Location' => "/people/5.#{format}"}
assert_equal ActiveResource::Response.new(ryan, 201, {'Location' => "/people/5.#{format}"}), remote_ryan.post(:register)
end
end
end
def test_setting_format_before_site
resource = Class.new(ActiveResource::Base)
resource.format = :json
resource.site = 'http://37s.sunrise.i:3000'
assert_equal ActiveResource::Formats[:json], resource.connection.format
end
private
def using_format(klass, mime_type_reference)
previous_format = klass.format