Skip to content

Commit

Permalink
Symbolize names and freeze values when loading from JSON
Browse files Browse the repository at this point in the history
JSON.load_file being defined implies that symbolize_names and freeze
options are supported at parse time. We use this as a best effort
feature test.
  • Loading branch information
paarthmadan committed Dec 13, 2021
1 parent 3ae91d3 commit 2ab9b37
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
7 changes: 6 additions & 1 deletion lib/i18n/backend/base.rb
Expand Up @@ -253,7 +253,12 @@ def load_yml(filename)
# toplevel keys.
def load_json(filename)
begin
::JSON.parse(File.read(filename))
# Use #load_file as a proxy for a version of JSON where symbolize_names and freeze are supported.
if JSON.respond_to?(:load_file)
::JSON.load_file(filename, symbolize_names: true, freeze: true)
else
::JSON.parse(File.read(filename))
end
rescue TypeError, StandardError => e
raise InvalidLocaleData.new(filename, e.inspect)
end
Expand Down
6 changes: 5 additions & 1 deletion test/backend/simple_test.rb
Expand Up @@ -77,7 +77,11 @@ def setup

test "simple load_json: loads data from a JSON file" do
data = I18n.backend.send(:load_json, "#{locales_dir}/en.json")
assert_equal({ 'en' => { 'foo' => { 'bar' => 'baz' } } }, data)
assert_equal({ :en => { :foo => { :bar => 'baz' } } }, data)

if JSON.respond_to?(:load_file)
assert_predicate data.dig(:en, :foo, :bar), :frozen?
end
end

test "simple load_translations: loads data from known file formats" do
Expand Down

0 comments on commit 2ab9b37

Please sign in to comment.