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 keys and freeze values when loading from YAML #583

Merged
merged 2 commits into from Jan 26, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 2 additions & 2 deletions lib/i18n/backend/base.rb
Expand Up @@ -240,7 +240,7 @@ def load_rb(filename)
def load_yml(filename)
begin
if YAML.respond_to?(:unsafe_load_file) # Psych 4.0 way
[YAML.unsafe_load_file(filename), false]
[YAML.unsafe_load_file(filename, symbolize_names: true, freeze: true), true]
else
[YAML.load_file(filename), false]
end
Expand All @@ -255,7 +255,7 @@ def load_yml(filename)
def load_json(filename)
begin
# Use #load_file as a proxy for a version of JSON where symbolize_names and freeze are supported.
if JSON.respond_to?(:load_file)
if ::JSON.respond_to?(:load_file)
[::JSON.load_file(filename, symbolize_names: true, freeze: true), true]
else
[::JSON.parse(File.read(filename)), false]
Expand Down
11 changes: 9 additions & 2 deletions test/backend/simple_test.rb
Expand Up @@ -92,15 +92,22 @@ def setup

test "simple load_yml: loads data from a YAML file" do
data, _ = I18n.backend.send(:load_yml, "#{locales_dir}/en.yml")
assert_equal({ 'en' => { 'foo' => { 'bar' => 'baz' } } }, data)
if ::YAML.respond_to?(:unsafe_load_file)
assert_equal({ :en => { :foo => { :bar => 'baz' } } }, data)
Copy link
Collaborator

@radar radar Dec 13, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd like a check for frozen values here too, please. I think this might work here:

assert data.dig(:en, :foo, :bar).frozen?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, added!

assert_predicate data.dig(:en, :foo, :bar), :frozen?
else
assert_equal({ 'en' => { 'foo' => { 'bar' => 'baz' } } }, data)
end
end

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)

if JSON.respond_to?(:load_file)
assert_equal({ :en => { :foo => { :bar => 'baz' } } }, data)
assert_predicate data.dig(:en, :foo, :bar), :frozen?
else
assert_equal({ 'en' => { 'foo' => { 'bar' => 'baz' } } }, data)
end
end

Expand Down