Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Symbolize names and freeze values when loading from JSON #587

Merged
merged 1 commit into from
Jan 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion lib/i18n/backend/base.rb
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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