Class: Mova::Interpolation::Sprintf
- Inherits:
-
Object
- Object
- Mova::Interpolation::Sprintf
- Includes:
- Overridable
- Defined in:
- lib/mova/interpolation/sprintf.rb
Overview
Wrapper around Kernel#sprintf with fallback for missing placeholders.
Defined Under Namespace
Modules: Overridable
Constant Summary collapse
- PLACEHOLDER_RE =
Regexp.union( /%%/, # escape character /%\{(\w+)\}/, # %{hello} /%<(\w+)>(.*?\d*\.?\d*[bBdiouxXeEfgGcps])/ # %<hello>.d )
- ESCAPE_SEQUENCE =
"%%".freeze
- ESCAPE_SEQUENCE_REPLACEMENT =
"%".freeze
Instance Method Summary collapse
-
#call(string, values) ⇒ String
Replaces each placeholder like “%{hello}” or “%<hello>3.0f” with given values.
Methods included from Overridable
Instance Method Details
#call(string, values) ⇒ String
Note:
Unlike ‘Kernel#sprintf` it won’t raise an exception in case of missing placeholder. Instead Mova::Interpolation::Sprintf::Overridable#missing_placeholder will be used to return a default replacement.
sprintf("Hello %{world}", other: "value") #=> KeyError: key{world} not found
interpolator.call("Hello %{world}", other: "value") #=> "Hello %{world}"
Replaces each placeholder like “%{hello}” or “%<hello>3.0f” with given values.
34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/mova/interpolation/sprintf.rb', line 34 def call(string, values) string.to_str.gsub(PLACEHOLDER_RE) do |match| if match == ESCAPE_SEQUENCE ESCAPE_SEQUENCE_REPLACEMENT else placeholder = ($1 || $2).to_sym replacement = values[placeholder] || missing_placeholder(placeholder, values, string) $3 ? sprintf("%#{$3}", replacement) : replacement end end end |