Skip to content

Commit

Permalink
Support XML and JSON inflector acronyms
Browse files Browse the repository at this point in the history
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
  • Loading branch information
seanpdoyle committed Jan 5, 2025
1 parent 9c8a2ee commit 9122780
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/active_resource/formats/json_format.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,7 @@ def decode(json)
Formats.remove_root(ActiveSupport::JSON.decode(json))
end
end

JSONFormat = JsonFormat
end
end
2 changes: 2 additions & 0 deletions lib/active_resource/formats/xml_format.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,7 @@ def decode(xml)
Formats.remove_root(Hash.from_xml(xml))
end
end

XMLFormat = XmlFormat
end
end
44 changes: 44 additions & 0 deletions test/cases/formats_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# frozen_string_literal: true

require "abstract_unit"

class FormatsTest < ActiveSupport::TestCase
def test_json_format_uses_camelcase
assert_equal ActiveResource::Formats::JsonFormat, ActiveResource::Formats[:json]
end

def test_xml_format_uses_camelcase
assert_equal ActiveResource::Formats::XmlFormat, ActiveResource::Formats[:xml]
end

def test_custom_format_uses_camelcase
klass = Class.new
ActiveResource::Formats.const_set(:MsgpackFormat, klass)

assert_equal klass, ActiveResource::Formats[:msgpack]
ensure
ActiveResource::Formats.send(:remove_const, :MsgpackFormat)
end

def test_unknown_format_raises_not_found_error
assert_raises NameError, match: "uninitialized constant ActiveResource::Formats::MsgpackFormat" do
ActiveResource::Formats[:msgpack]
end
end

def test_json_format_uses_acronym_inflections
ActiveSupport::Inflector.inflections { |inflect| inflect.acronym "JSON" }

assert_equal ActiveResource::Formats::JsonFormat, ActiveResource::Formats[:json]
ensure
ActiveSupport::Inflector.inflections.clear
end

def test_xml_format_uses_acronym_inflections
ActiveSupport::Inflector.inflections { |inflect| inflect.acronym "XML" }

assert_equal ActiveResource::Formats::XmlFormat, ActiveResource::Formats[:xml]
ensure
ActiveSupport::Inflector.inflections.clear
end
end

0 comments on commit 9122780

Please sign in to comment.