Module: StringInterpolation

Defined in:
lib/string-interpolation.rb

Overview

heavily based on Masao Mutoh’s gettext String interpolation extension github.com/mutoh/gettext/blob/f6566738b981fe0952548c421042ad1e0cdfb31e/lib/gettext/core_ext/string.rb

Constant Summary collapse

INTERPOLATION_PATTERN =
Regexp.union(
  /%%/,
  /%\{(\w+)\}/, # matches placeholders like "%{foo}"
  /%<(\w+)>(.*?\d*\.?\d*[bBdiouxXeEfgGcps])/ # matches placeholders like "%<foo>.d"
)

Class Method Summary collapse

Class Method Details

.interpolate(string, values, options = {}) ⇒ Object

Replace variables (defined in sprintf syntax) in given string with values from variables hash.

If variable value is not found there are 3 possible strategies (configurable via :value_not_found in third options argument):

  • :raise - raise argument error

  • :ignore - ignore the variable in string (leave as is, do not replace) (DEFAULT)

  • :hide - replace the variable in string with empty string

Raises:

  • (ArgumentError)


20
21
22
23
24
# File 'lib/string-interpolation.rb', line 20

def interpolate(string, values, options = {})
  options[:not_found_strategy] ||= :ignore
  raise ArgumentError.new('Interpolation values must be a Hash.') unless values.kind_of?(Hash)
  interpolate_hash(string, values, options)
end

.interpolate_hash(string, values, options) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/string-interpolation.rb', line 26

def interpolate_hash(string, values, options)
  string.gsub(INTERPOLATION_PATTERN) do |match|
    if match == '%%'
      '%'
    else
      key = ($1 || $2).to_sym
      if values.key?(key)
        value = values[key]
        value = value.call(values) if value.respond_to?(:call)
        $3 ? sprintf("%#{$3}", value) : value
      else
        if options[:not_found_strategy] == :raise
          raise ArgumentError.new("missing interpolation argument #{key} in #{string.inspect}. Given values are: (#{values.inspect})")
        elsif options[:not_found_strategy] == :hide
          value = ''
        else
          value = $&
        end
      end
    end
  end
end