Skip to content

Commit

Permalink
Remove procs from translations before exporting files. (#696)
Browse files Browse the repository at this point in the history
Close #690.
  • Loading branch information
fnando committed Dec 30, 2022
1 parent 09fe978 commit ca5591a
Show file tree
Hide file tree
Showing 6 changed files with 45 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -15,6 +15,7 @@ Prefix your message with one of the following:

- [Changed] Do not re-export files whose contents haven't changed.
- [Changed] Translations will always be deep sorted.
- [Fixed] Remove procs from translations before exporting files.

## v4.2.1 - Dec 25, 2022

Expand Down
3 changes: 2 additions & 1 deletion lib/i18n-js.rb
Expand Up @@ -14,6 +14,7 @@
require_relative "i18n-js/version"
require_relative "i18n-js/plugin"
require_relative "i18n-js/sort_hash"
require_relative "i18n-js/clean_hash"

module I18nJS
MissingConfigError = Class.new(StandardError)
Expand Down Expand Up @@ -52,7 +53,7 @@ def self.export_group(group)
end
end

filtered_translations = sort_hash(filtered_translations)
filtered_translations = sort_hash(clean_hash(filtered_translations))
output_file_path = File.expand_path(group[:file])
exported_files = []

Expand Down
13 changes: 13 additions & 0 deletions lib/i18n-js/clean_hash.rb
@@ -0,0 +1,13 @@
# frozen_string_literal: true

module I18nJS
def self.clean_hash(hash)
hash.keys.each_with_object({}) do |key, buffer|
value = hash[key]

next if value.is_a?(Proc)

buffer[key] = value.is_a?(Hash) ? clean_hash(value) : value
end
end
end
8 changes: 8 additions & 0 deletions test/fixtures/expected/clean_hash.json
@@ -0,0 +1,8 @@
{
"en": {
"a": 1,
"b": {
"d": 4
}
}
}
11 changes: 11 additions & 0 deletions test/i18n-js/clean_hash_test.rb
@@ -0,0 +1,11 @@
# frozen_string_literal: true

require "test_helper"

class CleanHashTest < Minitest::Test
test "removes non accepted values" do
expected = {b: {d: 4}}

assert_equal expected, I18nJS.clean_hash(a: -> { }, b: {c: -> { }, d: 4})
end
end
10 changes: 10 additions & 0 deletions test/i18n-js/exporter_test.rb
Expand Up @@ -231,4 +231,14 @@ def transform(translations:)
# mtime should be newer
assert File.mtime(exported_file_path) > exported_file_mtime
end

test "cleans hash when exporting files" do
I18n.backend.store_translations(:en, {a: 1, b: {c: -> { }, d: 4}})

actual_files = I18nJS.call(config_file: "./test/config/everything.yml")

assert_exported_files ["test/output/everything.json"], actual_files
assert_json_file "test/fixtures/expected/clean_hash.json",
"test/output/everything.json"
end
end

0 comments on commit ca5591a

Please sign in to comment.