Skip to content

Commit

Permalink
Sort translations after filtering them out.
Browse files Browse the repository at this point in the history
Close #691.
  • Loading branch information
fnando committed Dec 30, 2022
1 parent dedf5fd commit 29f9650
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/i18n-js.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
require_relative "i18n-js/schema"
require_relative "i18n-js/version"
require_relative "i18n-js/plugin"
require_relative "i18n-js/sort_hash"

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

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

Expand Down
12 changes: 12 additions & 0 deletions lib/i18n-js/sort_hash.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# frozen_string_literal: true

module I18nJS
def self.sort_hash(hash)
return hash unless hash.is_a?(Hash)

hash.keys.sort_by(&:to_s).each_with_object({}) do |key, seed|
value = hash[key]
seed[key] = value.is_a?(Hash) ? sort_hash(value) : value
end
end
end
21 changes: 21 additions & 0 deletions test/i18n-js/sort_hash_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# frozen_string_literal: true

require "test_helper"

class SortHashTest < Minitest::Test
test "returns non-hash objects" do
assert_equal 1, I18nJS.sort_hash(1)
end

test "sorts shallow hash" do
expected = {a: 1, b: 2, c: 3}

assert_equal expected, I18nJS.sort_hash(c: 3, a: 1, b: 2)
end

test "sorts nested hash" do
expected = {a: {b: 1, c: 2}, d: 3}

assert_equal expected, I18nJS.sort_hash(d: 3, a: {c: 2, b: 1})
end
end

0 comments on commit 29f9650

Please sign in to comment.