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

Regex part deux - INTERPOLATION_SYNTAX #669

Merged
merged 3 commits into from
Jun 21, 2023
Merged
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
12 changes: 5 additions & 7 deletions lib/i18n/backend/interpolation_compiler.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@ module InterpolationCompiler
module Compiler
extend self

TOKENIZER = /(%%\{[^\}]+\}|%\{[^\}]+\})/
INTERPOLATION_SYNTAX_PATTERN = /(%)?(%\{([^\}]+)\})/
TOKENIZER = /(%%?\{[^}]+\})/

def compile_if_an_interpolation(string)
if interpolated_str?(string)
Expand All @@ -37,7 +36,7 @@ def i18n_interpolate(v = {})
end

def interpolated_str?(str)
str.kind_of?(::String) && str =~ INTERPOLATION_SYNTAX_PATTERN
str.kind_of?(::String) && str =~ TOKENIZER
end

protected
Expand All @@ -48,13 +47,12 @@ def tokenize(str)

def compiled_interpolation_body(str)
tokenize(str).map do |token|
(matchdata = token.match(INTERPOLATION_SYNTAX_PATTERN)) ? handle_interpolation_token(token, matchdata) : escape_plain_str(token)
token.match(TOKENIZER) ? handle_interpolation_token(token) : escape_plain_str(token)
end.join
end

def handle_interpolation_token(interpolation, matchdata)
escaped, pattern, key = matchdata.values_at(1, 2, 3)
escaped ? pattern : compile_interpolation_token(key.to_sym)
def handle_interpolation_token(token)
token.start_with?('%%') ? token[1..] : compile_interpolation_token(token[2..-2])
end

def compile_interpolation_token(key)
Expand Down