Skip to content

Commit a7fc163

Browse files
author
Ethan Langevin
committed
Added more tests
1 parent 68d6d95 commit a7fc163

File tree

2 files changed

+40
-5
lines changed

2 files changed

+40
-5
lines changed

lib/roar/rails/formats.rb

+15-5
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ def find_namespaced_class(basis, to_find)
6868
ancestor_mods = build_ancestor_modules(basis)
6969
namespace = find_class_in_namespaces(ancestor_mods, to_find)
7070

71-
namespace.nil? ? to_find.constantize : namespace.const_get(to_find)
71+
namespace.nil? ? to_find.constantize : get_constant(namespace, to_find)
7272
end
7373

7474
def build_ancestor_modules(basis)
@@ -88,12 +88,22 @@ def build_ancestor_modules(basis)
8888

8989
def find_class_in_namespaces(modules, class_name)
9090
modules.reverse.detect do |ns|
91-
begin
92-
ns.const_get(class_name, false)
93-
rescue NameError
94-
nil
91+
get_constant(ns, class_name)
92+
end
93+
end
94+
95+
# Used to patch different behavior between
96+
# different versions of ruby when looking up a
97+
# constant like V1::Singer
98+
def get_constant(basis, class_string)
99+
begin
100+
class_string.split('::').reduce(basis) do |basis, const|
101+
basis.const_get(const, false)
95102
end
103+
rescue NameError
104+
nil
96105
end
106+
97107
end
98108

99109
class Path < String

test/formats_test.rb

+25
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,10 @@ module V1
1111
SingerRepresenter = Class.new
1212
BassistRepresenter = Class.new
1313
SingersRepresenter = Class.new
14+
15+
module Inner
16+
SingerRepresenter = Class.new
17+
end
1418
end
1519

1620
module V2
@@ -19,6 +23,15 @@ module V2
1923
SingersRepresenter = Class.new
2024
end
2125

26+
module Inner
27+
Singer = Class.new
28+
end
29+
30+
module Outer
31+
Singer = Class.new
32+
SingerRepresenter = Class.new
33+
end
34+
2235
Bassist = Class.new
2336

2437
class FormatsTest < MiniTest::Spec
@@ -106,6 +119,18 @@ class FormatsTest < MiniTest::Spec
106119
it 'finds the right class in another namespace' do
107120
subject.for(:json, V2::Singer.new, 'v1/singers').must_equal V2::SingerRepresenter
108121
end
122+
123+
it 'finds the right class in an inner namespace' do
124+
subject.for(:json, Inner::Singer.new, 'v1/singers').must_equal V1::Inner::SingerRepresenter
125+
end
126+
127+
it 'finds the right class from the root namespace' do
128+
subject.for(:json, Outer::Singer.new, 'v1/singers').must_equal Outer::SingerRepresenter
129+
end
130+
131+
it 'finds the right class in a deep namespace' do
132+
subject.for(:json, Singer.new, 'v1/inner/singers').must_equal V1::Inner::SingerRepresenter
133+
end
109134
end
110135
end
111136

0 commit comments

Comments
 (0)