class Mova::Interpolation::Sprintf

Wrapper around {ruby-doc.org/core/Kernel.html#method-i-sprintf Kernel#sprintf} with fallback for missing placeholders.

@since 0.1.0

Constants

ESCAPE_SEQUENCE
ESCAPE_SEQUENCE_REPLACEMENT
PLACEHOLDER_RE

Public Instance Methods

call(string, values) click to toggle source

Replaces each placeholder like “%{{hello}}” or “%<hello>3.0f” with given values. @return [String] @param string [String] @param values [Hash{Symbol => String}]

@example

interpolator.call("Hello, %{you}!", you: "world") #=> "Hello, world!"

@example Sprintf-like formatting

# this is the equivalent to `sprintf("%3.0f", 1.0)`
interpolator.call("%<num>3.0f", num: 1.0) #=> "  1"

@note Unlike ‘Kernel#sprintf` it won’t raise an exception in case of missing

placeholder. Instead {#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}"

@see ruby-doc.org/core/Kernel.html#method-i-sprintf

# 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