Created
October 22, 2021 23:28
-
-
Save westonganger/255b45895101403d3760e2e62fae1e29 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ### Adapted from below, custom changes marked with "CUSTOM" | |
| ### https://github.com/electric-feel/i18n-backend-side_by_side/blob/master/lib/i18n/backend/side_by_side.rb | |
| require 'i18n' | |
| require 'i18n/core_ext/hash' | |
| module I18n | |
| module Backend | |
| using HashRefinements | |
| class SideBySide < Simple | |
| #VERSION = File.read(File.expand_path('../../../../VERSION', __FILE__)) | |
| LOCALE_PREFIX = '_' | |
| protected | |
| def load_file(filename) | |
| type = File.extname(filename).tr('.', '').downcase | |
| unless respond_to?(:"load_#{type}", true) | |
| raise UnknownFileType.new(type, filename) | |
| end | |
| data = send(:"load_#{type}", filename) | |
| unless data.is_a?(Hash) | |
| raise InvalidLocaleData.new(filename, 'expects it to return a hash, but does not') | |
| end | |
| if data.first.first == LOCALE_PREFIX | |
| _process([], data[LOCALE_PREFIX].deep_symbolize_keys) | |
| else | |
| data.each { |locale, d| store_translations(locale, d || {}) } | |
| end | |
| end | |
| private | |
| def _process(path, hash) | |
| if !hash.is_a?(Hash) ### CUSTOM | |
| value = hash | |
| translations.keys.each do |locale| | |
| _store([locale] + path, value) | |
| end | |
| elsif _contains_locales?(hash) | |
| hash.each do |locale, value| | |
| _store([_strip_locale_prefix(locale)] + path, value) | |
| end | |
| else | |
| hash.each { |key, value| _process(path + [key], value) } | |
| end | |
| end | |
| def _store(path, value) | |
| *keys, last_key = path | |
| target = keys.inject(translations) do |hash, key| | |
| hash[key] ||= {} | |
| hash[key] | |
| end | |
| target[last_key] = value | |
| end | |
| def _contains_locales?(hash) | |
| hash.first.first[0] == LOCALE_PREFIX | |
| end | |
| def _strip_locale_prefix(locale) | |
| locale[LOCALE_PREFIX.length..-1].to_sym | |
| end | |
| end | |
| end | |
| end | |
| ### USE NEW BACKEND | |
| I18n.backend = I18n::Backend::SideBySide.new |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment