Skip to content

Commit c65cc65

Browse files
committed
Support XML and JSON inflector acronyms
Related to #361 Add special-case treatment of JSON and XML acronyms by declaring aliases for the `JsonFormat` and `XmlFormat` constants. In addition to the aliases, this commit also includes test coverage to cover existing behavior. The original PR included a comment citing that `ActiveSupport::Inflector::Inflections#clear` was not working as expected. It was resolved by [a76344f][], which was merged into `main` prior to the `7.0.0` release. Since the CI matrix currently includes `7-0-stable` as the minimum version, the code can rely on the resolved behavior. [a76344f]: rails/rails@a76344f
1 parent 9c8a2ee commit c65cc65

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

lib/active_resource/formats/json_format.rb

+2
Original file line numberDiff line numberDiff line change
@@ -24,5 +24,7 @@ def decode(json)
2424
Formats.remove_root(ActiveSupport::JSON.decode(json))
2525
end
2626
end
27+
28+
JSONFormat = JsonFormat
2729
end
2830
end

lib/active_resource/formats/xml_format.rb

+2
Original file line numberDiff line numberDiff line change
@@ -23,5 +23,7 @@ def decode(xml)
2323
Formats.remove_root(Hash.from_xml(xml))
2424
end
2525
end
26+
27+
XMLFormat = XmlFormat
2628
end
2729
end

test/cases/formats_test.rb

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# frozen_string_literal: true
2+
3+
require "abstract_unit"
4+
5+
class FormatsTest < ActiveSupport::TestCase
6+
def test_json_format_uses_camelcase
7+
assert_equal ActiveResource::Formats::JsonFormat, ActiveResource::Formats[:json]
8+
end
9+
10+
def test_xml_format_uses_camelcase
11+
assert_equal ActiveResource::Formats::XmlFormat, ActiveResource::Formats[:xml]
12+
end
13+
14+
def test_custom_format_uses_camelcase
15+
klass = Class.new
16+
ActiveResource::Formats.const_set(:MsgpackFormat, klass)
17+
18+
assert_equal klass, ActiveResource::Formats[:msgpack]
19+
ensure
20+
ActiveResource::Formats.send(:remove_const, :MsgpackFormat)
21+
end
22+
23+
def test_unknown_format_raises_not_found_error
24+
assert_raises NameError, match: "uninitialized constant ActiveResource::Formats::MsgpackFormat" do
25+
ActiveResource::Formats[:msgpack]
26+
end
27+
end
28+
29+
def test_json_format_uses_acronym_inflections
30+
ActiveSupport::Inflector.inflections { |inflect| inflect.acronym "JSON" }
31+
32+
assert_equal ActiveResource::Formats::JsonFormat, ActiveResource::Formats[:json]
33+
ensure
34+
ActiveSupport::Inflector.inflections.clear :acronyms
35+
end
36+
37+
def test_xml_format_uses_acronym_inflections
38+
ActiveSupport::Inflector.inflections { |inflect| inflect.acronym "XML" }
39+
40+
assert_equal ActiveResource::Formats::XmlFormat, ActiveResource::Formats[:xml]
41+
ensure
42+
ActiveSupport::Inflector.inflections.clear :acronyms
43+
end
44+
end

0 commit comments

Comments
 (0)