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

API for marking a key as reserved #579

Merged
merged 1 commit into from
Jan 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions lib/i18n.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,26 @@ module I18n
scope
separator
throw
].freeze
RESERVED_KEYS_PATTERN = /%\{(#{RESERVED_KEYS.join("|")})\}/
]
EMPTY_HASH = {}.freeze

def self.new_double_nested_cache # :nodoc:
Concurrent::Map.new { |h, k| h[k] = Concurrent::Map.new }
end

# Marks a key as reserved. Reserved keys are used internally,
# and can't also be used for interpolation. If you are using any
# extra keys as I18n options, you should call I18n.reserve_key
# before any I18n.translate (etc) calls are made.
def self.reserve_key(key)
RESERVED_KEYS << key.to_sym
@reserved_keys_pattern = nil
end

def self.reserved_keys_pattern # :nodoc:
@reserved_keys_pattern ||= /%\{(#{RESERVED_KEYS.join("|")})\}/
end

module Base
# Gets I18n configuration object.
def config
Expand Down
2 changes: 1 addition & 1 deletion lib/i18n/interpolate/ruby.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class << self
# Return String or raises MissingInterpolationArgument exception.
# Missing argument's logic is handled by I18n.config.missing_interpolation_argument_handler.
def interpolate(string, values)
raise ReservedInterpolationKey.new($1.to_sym, string) if string =~ RESERVED_KEYS_PATTERN
raise ReservedInterpolationKey.new($1.to_sym, string) if string =~ I18n.reserved_keys_pattern
raise ArgumentError.new('Interpolation values must be a Hash.') unless values.kind_of?(Hash)
interpolate_hash(string, values)
end
Expand Down
18 changes: 18 additions & 0 deletions test/i18n_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -487,4 +487,22 @@ def call(exception, locale, key, options); key; end
I18n.enforce_available_locales = false
end
end

test "can reserve a key" do
begin
reserved_keys_were = I18n::RESERVED_KEYS.dup

assert !I18n::RESERVED_KEYS.include?(:foo)
assert !I18n::RESERVED_KEYS.include?(:bar)

I18n.reserve_key(:foo)
I18n.reserve_key("bar")

assert I18n::RESERVED_KEYS.include?(:foo)
assert I18n::RESERVED_KEYS.include?(:bar)
ensure
I18n::RESERVED_KEYS = reserved_keys_were
I18n.instance_variable_set(:@reserved_keys_pattern, nil)
end
end
end