Skip to content

Commit f21d50a

Browse files
authored
Merge pull request #416 from seanpdoyle/acronym-support
Support XML and JSON inflector acronyms
2 parents 6dcd314 + a90bf24 commit f21d50a

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

lib/active_resource/formats.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,11 @@ module Formats
1010
# ActiveResource::Formats[:xml] # => ActiveResource::Formats::XmlFormat
1111
# ActiveResource::Formats[:json] # => ActiveResource::Formats::JsonFormat
1212
def self.[](mime_type_reference)
13-
ActiveResource::Formats.const_get(ActiveSupport::Inflector.camelize(mime_type_reference.to_s) + "Format")
13+
case mime_type_reference.to_s
14+
when "xml" then XmlFormat
15+
when "json" then JsonFormat
16+
else ActiveResource::Formats.const_get(ActiveSupport::Inflector.camelize(mime_type_reference.to_s) + "Format")
17+
end
1418
end
1519

1620
def self.remove_root(data)

test/cases/formats_test.rb

Lines changed: 44 additions & 0 deletions
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)