Skip to content

Commit 1e87d58

Browse files
asonixchingor13
authored andcommitted
Format belongs_to URLs (#260)
* Format belongs_to URLs * Add test to ensure belongs_to URLs get formatted
1 parent f62e472 commit 1e87d58

File tree

3 files changed

+40
-6
lines changed

3 files changed

+40
-6
lines changed

lib/json_api_client/associations/belongs_to.rb

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,13 @@ def param
1616
:"#{attr_name}_id"
1717
end
1818

19-
def to_prefix_path
20-
"#{attr_name.to_s.pluralize}/%{#{param}}"
19+
def to_prefix_path(formatter)
20+
"#{formatter.format(attr_name.to_s.pluralize)}/%{#{param}}"
2121
end
2222

23-
def set_prefix_path(attrs)
23+
def set_prefix_path(attrs, formatter)
2424
attrs[param] = encode_part(attrs[param]) if attrs.key?(param)
25-
to_prefix_path % attrs
25+
to_prefix_path(formatter) % attrs
2626
end
2727
end
2828
end

lib/json_api_client/resource.rb

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -263,11 +263,19 @@ def _belongs_to_associations
263263
end
264264

265265
def _prefix_path
266-
_belongs_to_associations.map(&:to_prefix_path).join("/")
266+
paths = _belongs_to_associations.map do |a|
267+
a.to_prefix_path(route_formatter)
268+
end
269+
270+
paths.join("/")
267271
end
268272

269273
def _set_prefix_path(attrs)
270-
_belongs_to_associations.map { |a| a.set_prefix_path(attrs) }.join("/")
274+
paths = _belongs_to_associations.map do |a|
275+
a.set_prefix_path(attrs, route_formatter)
276+
end
277+
278+
paths.join("/")
271279
end
272280

273281
def _new_scope

test/unit/association_test.rb

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,34 @@ class Property < TestResource
3131
end
3232
end
3333

34+
class Formatted < TestResource
35+
def self.key_formatter
36+
JsonApiClient::DasherizedKeyFormatter
37+
end
38+
39+
def self.route_formatter
40+
JsonApiClient::DasherizedRouteFormatter
41+
end
42+
end
43+
44+
class MultiWordParent < Formatted
45+
end
46+
47+
class MultiWordChild < Formatted
48+
belongs_to :multi_word_parent
49+
end
50+
3451
class AssociationTest < MiniTest::Test
3552

53+
def test_belongs_to_urls_are_formatted
54+
request = stub_request(:get, "http://example.com/multi-word-parents/1/multi-word-children")
55+
.to_return(headers: {content_type: "application/vnd.api+json"}, body: { data: [] }.to_json)
56+
57+
MultiWordChild.where(multi_word_parent_id: 1).to_a
58+
59+
assert_requested(request)
60+
end
61+
3662
def test_load_has_one
3763
stub_request(:get, "http://example.com/properties/1")
3864
.to_return(headers: {content_type: "application/vnd.api+json"}, body: {

0 commit comments

Comments
 (0)