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
-
.interpolate(string, values, options = {}) ⇒ Object
Replace variables (defined in sprintf syntax) in given string with values from variables hash.
- .interpolate_hash(string, values, options) ⇒ Object
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
20 21 22 23 24 |
# File 'lib/string-interpolation.rb', line 20 def interpolate(string, values, = {}) [:not_found_strategy] ||= :ignore raise ArgumentError.new('Interpolation values must be a Hash.') unless values.kind_of?(Hash) interpolate_hash(string, values, ) 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, ) 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 [:not_found_strategy] == :raise raise ArgumentError.new("missing interpolation argument #{key} in #{string.inspect}. Given values are: (#{values.inspect})") elsif [:not_found_strategy] == :hide value = '' else value = $& end end end end end |