Skip to content

Commit

Permalink
Added more tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Ethan Langevin committed Aug 27, 2014
1 parent 68d6d95 commit a7fc163
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 5 deletions.
20 changes: 15 additions & 5 deletions lib/roar/rails/formats.rb
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def find_namespaced_class(basis, to_find)
ancestor_mods = build_ancestor_modules(basis)
namespace = find_class_in_namespaces(ancestor_mods, to_find)

namespace.nil? ? to_find.constantize : namespace.const_get(to_find)
namespace.nil? ? to_find.constantize : get_constant(namespace, to_find)
end

def build_ancestor_modules(basis)
Expand All @@ -88,12 +88,22 @@ def build_ancestor_modules(basis)

def find_class_in_namespaces(modules, class_name)
modules.reverse.detect do |ns|
begin
ns.const_get(class_name, false)
rescue NameError
nil
get_constant(ns, class_name)
end
end

# Used to patch different behavior between
# different versions of ruby when looking up a
# constant like V1::Singer
def get_constant(basis, class_string)
begin
class_string.split('::').reduce(basis) do |basis, const|
basis.const_get(const, false)
end
rescue NameError
nil
end

end

class Path < String
Expand Down
25 changes: 25 additions & 0 deletions test/formats_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ module V1
SingerRepresenter = Class.new
BassistRepresenter = Class.new
SingersRepresenter = Class.new

module Inner
SingerRepresenter = Class.new
end
end

module V2
Expand All @@ -19,6 +23,15 @@ module V2
SingersRepresenter = Class.new
end

module Inner
Singer = Class.new
end

module Outer
Singer = Class.new
SingerRepresenter = Class.new
end

Bassist = Class.new

class FormatsTest < MiniTest::Spec
Expand Down Expand Up @@ -106,6 +119,18 @@ class FormatsTest < MiniTest::Spec
it 'finds the right class in another namespace' do
subject.for(:json, V2::Singer.new, 'v1/singers').must_equal V2::SingerRepresenter
end

it 'finds the right class in an inner namespace' do
subject.for(:json, Inner::Singer.new, 'v1/singers').must_equal V1::Inner::SingerRepresenter
end

it 'finds the right class from the root namespace' do
subject.for(:json, Outer::Singer.new, 'v1/singers').must_equal Outer::SingerRepresenter
end

it 'finds the right class in a deep namespace' do
subject.for(:json, Singer.new, 'v1/inner/singers').must_equal V1::Inner::SingerRepresenter
end
end
end

Expand Down

0 comments on commit a7fc163

Please sign in to comment.