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

Bug: deep sorting for keys missed #691

Closed
oleksii-leonov opened this issue Dec 30, 2022 · 2 comments · Fixed by #695
Closed

Bug: deep sorting for keys missed #691

oleksii-leonov opened this issue Dec 30, 2022 · 2 comments · Fixed by #695

Comments

@oleksii-leonov
Copy link
Contributor

Description

In v3, localization keys were deeply sorted:

def self.deep_key_sort(hash)

It's useful to guarantee that exported JSON files would be byte-to-byte equal.

How to reproduce

Export JSON localization with v4.

What do you expect

Same behavior as v3, with deeply sorted localization keys.

What happened instead

Localization keys are not sorted.

Software:

  • Gem version: 4.2.1
  • Ruby version: 3.1.3
@oleksii-leonov
Copy link
Contributor Author

I am not sure that deep keys sorting should be in the core.
Adding it as a default plugin could be good enough.

# frozen_string_literal: true

module I18nJS
  require "i18n-js/plugin"

  class SortKeysPlugin < I18nJS::Plugin
    module Utils
      # https://github.com/fnando/i18n-js/blob/4b07b30e8b6f42c4415f4bb967e8e2986a0e2268/lib/i18n/js/utils.rb#L68
      def self.deep_key_sort(hash)
        hash.keys.sort_by(&:to_s).each_with_object({}) do |key, seed|
          value = hash[key]
          seed[key] = value.is_a?(Hash) ? deep_key_sort(value) : value
        end
      end
    end

    def transform(translations:)
      return translations unless enabled?

      Utils.deep_key_sort(translations)
    end

    def setup
      I18nJS::Schema.root_keys << config_key
    end

    def validate_schema
      valid_keys = %i[enabled]

      schema.expect_required_keys(keys: valid_keys, path: [config_key])
      schema.reject_extraneous_keys(keys: valid_keys, path: [config_key])
    end
  end
end

@fnando
Copy link
Owner

fnando commented Dec 30, 2022

This should definitely be a core, non-removable feature (tbh, I thought I had added it already, but I guess I didn't).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants