Class: Mova::Interpolation::Sprintf

Inherits:
Object
  • Object
show all
Includes:
Overridable
Defined in:
lib/mova/interpolation/sprintf.rb

Overview

Wrapper around Kernel#sprintf with fallback for missing placeholders.

Since:

  • 0.1.0

Defined Under Namespace

Modules: Overridable

Constant Summary collapse

PLACEHOLDER_RE =

Since:

  • 0.1.0

Regexp.union(
  /%%/,         # escape character
  /%\{(\w+)\}/, # %{hello}
  /%<(\w+)>(.*?\d*\.?\d*[bBdiouxXeEfgGcps])/ # %<hello>.d
)
ESCAPE_SEQUENCE =

Since:

  • 0.1.0

"%%".freeze
ESCAPE_SEQUENCE_REPLACEMENT =

Since:

  • 0.1.0

"%".freeze

Instance Method Summary collapse

Methods included from Overridable

#missing_placeholder

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.

Examples:

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

Sprintf-like formatting

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

Parameters:

  • string (String)
  • values (Hash{Symbol => String})

Returns:

  • (String)

See Also:

Since:

  • 0.1.0



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