Fix broken module namespacing in ActiveResource with Ruby 1.9 [#5699 state:resolved]

Following namespace use case was broken with Ruby 1.9:

  class Author < ActiveRecord::Base
    ...
  end

  module Api
    class Book < ActiveResouce::Base
    end
  end

Let's say XML contains <book><author><name>John</name></author>....

  Api::Book.first.author.class.to_s #=>
    Ruby 1.8.7: "Api::Book::Author" (namespaced, correct),
    Ruby 1.9: "Author" (toplevel, broken)

Signed-off-by: José Valim <jose.valim@gmail.com>
This commit is contained in:
Matthijs Langenberg 2010-09-24 22:37:26 +02:00 committed by José Valim
parent dd83140b24
commit 67a838574b
4 changed files with 22 additions and 5 deletions

View File

@ -1374,8 +1374,9 @@ module ActiveResource
namespaces = module_names[0, module_names.size-1].map do |module_name|
receiver = receiver.const_get(module_name)
end
if namespace = namespaces.reverse.detect { |ns| ns.const_defined?(resource_name) }
return namespace.const_get(resource_name)
const_args = RUBY_VERSION < "1.9" ? [resource_name] : [resource_name, false]
if namespace = namespaces.reverse.detect { |ns| ns.const_defined?(*const_args) }
return namespace.const_get(*const_args)
else
raise NameError
end
@ -1391,8 +1392,9 @@ module ActiveResource
self.class.const_get(resource_name)
end
rescue NameError
if self.class.const_defined?(resource_name)
resource = self.class.const_get(resource_name)
const_args = RUBY_VERSION < "1.9" ? [resource_name] : [resource_name, false]
if self.class.const_defined?(*const_args)
resource = self.class.const_get(*const_args)
else
resource = self.class.const_set(resource_name, Class.new(ActiveResource::Base))
end

View File

@ -75,6 +75,10 @@ def setup_response
</person>
eof
@startup_sound = {
:name => "Mac Startup Sound", :author => { :name => "Jim Reekes" }
}.to_xml(:root => 'sound')
ActiveResource::HttpMock.respond_to do |mock|
mock.get "/people/1.xml", {}, @matz
mock.get "/people/2.xml", {}, @david
@ -112,6 +116,8 @@ def setup_response
mock.head "/people/Greg/addresses/1.xml", {}, nil, 200
# customer
mock.get "/customers/1.xml", {}, @luis
# sound
mock.get "/sounds/1.xml", {}, @startup_sound
end
Person.user = nil

View File

@ -1097,4 +1097,9 @@ class BaseTest < Test::Unit::TestCase
plan.save!
assert_equal 10.00, plan.price
end
def test_namespacing
sound = Asset::Sound.find(1)
assert_equal "Asset::Sound::Author", sound.author.class.to_s
end
end

View File

@ -1,5 +1,9 @@
module Asset
module Asset
class Sound < ActiveResource::Base
self.site = "http://37s.sunrise.i:3000"
end
end
# to test namespacing in a module
class Author
end