Skip to content

Commit

Permalink
Add I18n.interpolation_keys
Browse files Browse the repository at this point in the history
  • Loading branch information
tom-lord committed Mar 1, 2024
1 parent baf8a88 commit d55f40a
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions lib/i18n.rb
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,31 @@ def translate!(key, **options)
end
alias :t! :translate!

# Returns an array of interpolation keys for the given translation key
#
# Suppose we have the following:
# I18n.t 'example.zero' == 'Zero interpolations'
# I18n.t 'example.one' == 'One interpolation %{foo}'
# I18n.t 'example.two' == 'Two interpolations %{foo} %{bar}'
# I18n.t 'example.one', locale: :other == 'One interpolation %{baz} %{bar}'
#
# Then we can expect the following results:
# I18n.interpolation_keys('example.zero') #=> []
# I18n.interpolation_keys('example.one') #=> ['foo']
# I18n.interpolation_keys('example.two') #=> ['foo', 'bar']
# I18n.interpolation_keys('one', scope: 'example', locale: :other) #=> ['baz']
# I18n.interpolation_keys('does-not-exist') #=> []
def interpolation_keys(key, **options)
raise I18n::ArgumentError if !key.is_a?(String) || key.empty?

return [] unless exists?(key, **options.slice(:locale, :scope))

translate(key, **options.slice(:locale, :scope))
.scan(Regexp.union(I18n.config.interpolation_patterns))
.flatten
.compact
end

# Returns true if a translation exists for a given key, otherwise returns false.
def exists?(key, _locale = nil, locale: _locale, **options)
locale ||= config.locale
Expand Down

0 comments on commit d55f40a

Please sign in to comment.