module I18n::Backend::InterpolationCompiler::Compiler

Constants

TOKENIZER

Public Instance Methods

# File lib/i18n/backend/interpolation_compiler.rb, line 26
        def compile_if_an_interpolation(string)
          if interpolated_str?(string)
            string.instance_eval <<-RUBY_EVAL, __FILE__, __LINE__
              def i18n_interpolate(v = {})
                "#{compiled_interpolation_body(string)}"
              end
            RUBY_EVAL
          end

          string
        end
# File lib/i18n/backend/interpolation_compiler.rb, line 38
def interpolated_str?(str)
  str.kind_of?(::String) && str =~ TOKENIZER
end

Protected Instance Methods

# File lib/i18n/backend/interpolation_compiler.rb, line 58
def compile_interpolation_token(key)
  "\#{#{interpolate_or_raise_missing(key)}}"
end
# File lib/i18n/backend/interpolation_compiler.rb, line 48
def compiled_interpolation_body(str)
  tokenize(str).map do |token|
    token.match(TOKENIZER) ? handle_interpolation_token(token) : escape_plain_str(token)
  end.join
end
# File lib/i18n/backend/interpolation_compiler.rb, line 71
def direct_key(key)
  "((t = v[#{key}]) && t.respond_to?(:call) ? t.call : t)"
end
# File lib/i18n/backend/interpolation_compiler.rb, line 91
def escape_key_sym(key)
  # rely on Ruby to do all the hard work :)
  key.to_sym.inspect
end
# File lib/i18n/backend/interpolation_compiler.rb, line 87
def escape_plain_str(str)
  str.gsub(/"|\\|#/) {|x| "\\#{x}"}
end
# File lib/i18n/backend/interpolation_compiler.rb, line 54
def handle_interpolation_token(token)
  token.start_with?('%%') ? token[1..] : compile_interpolation_token(token[2..-2])
end
# File lib/i18n/backend/interpolation_compiler.rb, line 67
def interpolate_key(key)
  [direct_key(key), nil_key(key), missing_key(key)].join('||')
end
# File lib/i18n/backend/interpolation_compiler.rb, line 62
def interpolate_or_raise_missing(key)
  escaped_key = escape_key_sym(key)
  RESERVED_KEYS.include?(key) ? reserved_key(escaped_key) : interpolate_key(escaped_key)
end
# File lib/i18n/backend/interpolation_compiler.rb, line 79
def missing_key(key)
  "I18n.config.missing_interpolation_argument_handler.call(#{key}, v, self)"
end
# File lib/i18n/backend/interpolation_compiler.rb, line 75
def nil_key(key)
  "(v.has_key?(#{key}) && '')"
end
# File lib/i18n/backend/interpolation_compiler.rb, line 83
def reserved_key(key)
  "raise(ReservedInterpolationKey.new(#{key}, self))"
end

tokenize(“foo %{bar} baz %%{buz}”) # => [“foo ”, “%{bar}”, “ baz ”, “%%{buz}”]

# File lib/i18n/backend/interpolation_compiler.rb, line 44
def tokenize(str)
  str.split(TOKENIZER)
end