Class: SecretConfig::StringInterpolator

Inherits:
Object
  • Object
show all
Defined in:
lib/secret_config/string_interpolator.rb

Direct Known Subclasses

SettingInterpolator

Instance Method Summary collapse

Constructor Details

#initialize(pattern = nil) ⇒ StringInterpolator

Returns a new instance of StringInterpolator.



13
14
15
# File 'lib/secret_config/string_interpolator.rb', line 13

def initialize(pattern = nil)
  @pattern = pattern || /\${1,2}\{([^}]+)\}/
end

Instance Method Details

#parse(string) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/secret_config/string_interpolator.rb', line 17

def parse(string)
  string.gsub(/\${1,2}\{([^}]+)\}/) do |match|
    if match.start_with?("$$")
      match[1..-1]
    else
      expr          = Regexp.last_match(1) || Regexp.last_match(2) || match.tr("${}", "")
      key, args_str = expr.split(":")
      key           = key.strip.to_sym
      arguments     = args_str&.split(",")&.map { |v| v.strip == "" ? nil : v.strip } || []
      raise(InvalidInterpolation, "Invalid key: #{key} in string: #{match}") unless respond_to?(key)

      public_send(key, *arguments)
    end
  end
end