Skip to content

Instantly share code, notes, and snippets.

@dapi
Created March 30, 2022 10:40
Show Gist options
  • Save dapi/f379431a014ab23c639cc5dd7d2129ef to your computer and use it in GitHub Desktop.
Save dapi/f379431a014ab23c639cc5dd7d2129ef to your computer and use it in GitHub Desktop.
module I18n
extend CurrentVendor
# Implemented to support method call on translation keys
INTERPOLATION_WITH_METHOD_PATTERN = Regexp.union(
/%%/,
/%\{(\w+)\}/, # matches placeholders like "%{foo}"
/%<(\w+)>(.*?\d*\.?\d*[bBdiouxXeEfgGcps])/, # matches placeholders like "%<foo>.d"
/%\{(\w+)\.(\w+)\}/ # matches placeholders like "%{foo.upcase}"
)
class << self
def interpolate_hash(string, values)
string.gsub(INTERPOLATION_WITH_METHOD_PATTERN) do |match|
if match == '%%'
'%'
else
key = (Regexp.last_match[1] || Regexp.last_match[2] || Regexp.last_match[4]).to_sym
value = values.key?(key) ? values[key] : "%{#{key}}" # raise(MissingInterpolationArgument.new(key, values, string))
value = value.call(values) if value.respond_to?(:call)
if Regexp.last_match[3]
"%#{Regexp.last_match[3]}" % value
else
(Regexp.last_match[5] ? value.send(Regexp.last_match[5]) : value)
end
end
end
end
# Точная копия translate, только с нужным backend-ом
def vt(*args)
options = args.last.is_a?(Hash) ? args.pop.dup : {}
key = args.shift
backend = current_vendor.i18n
locale = options.delete(:locale) || config.locale
handling = (options.delete(:throw) && :throw) || (options.delete(:raise) && :raise) # TODO deprecate :raise
enforce_available_locales!(locale)
raise I18n::ArgumentError if key.is_a?(String) && key.empty?
result = catch(:exception) do
if key.is_a?(Array)
key.map { |k| backend.translate(locale, k, options) }
else
backend.translate(locale, key, options)
end
end
result.is_a?(MissingTranslation) ? handle_exception(handling, result, locale, key, options) : result
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment