Module: Interpolation

Included in:
Log3mf
Defined in:
lib/ruby3mf/interpolation.rb

Constant Summary collapse

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

Instance Method Summary collapse

Instance Method Details

#interpolate(string, values = {}) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/ruby3mf/interpolation.rb', line 9

def interpolate(string, values = {})
  string.gsub(INTERPOLATION_PATTERN) do |match|
    if match == '%%'
      '%'
    else
      key = ($1 || $2 || match.tr("%{}", "")).to_sym
      value = values[key]
      value = value.call(values) if value.respond_to?(:call)
      $3 ? sprintf("%#{$3}", value) : value
    end
  end
end

#map_value(thing) ⇒ Object



28
29
30
31
32
33
34
35
36
37
# File 'lib/ruby3mf/interpolation.rb', line 28

def map_value(thing)
  case thing
  when Hash
    symbolize_recursive(thing)
  when Array
    thing.map { |v| map_value(v) }
  else
    thing
  end
end

#symbolize_recursive(hash) ⇒ Object



22
23
24
25
26
# File 'lib/ruby3mf/interpolation.rb', line 22

def symbolize_recursive(hash)
  {}.tap do |h|
    hash.each { |key, value| h[key.to_sym] = map_value(value) }
  end
end