Top Level Namespace

Includes:
Constrain, ForwardTo, String::Text

Defined Under Namespace

Modules: Command, Fmt, FormatterOverrides, Prick, Timer Classes: IO, String

Instance Method Summary collapse

Instance Method Details

#expand_variables(str, variables) ⇒ Object

Expands variables in a template string. Variables are prefixed with a $ sign and consist of word characters (letters, digits, underscores). The name can be enclosed in curly braces to avoid unintended expansions. The $ sign can be escaped with a backslash (), and backslashes can be escaped with another backslash. All occurrences of a variable in the string are replaced

The str argument is the template string and the variables argument is a hash from variable name (String) to variable value

Note that the characters ‘x00’ and ‘x01’ are used internally and may not be present in the template string



14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/prick/ext/expand_variables.rb', line 14

def expand_variables(str, variables) # ChatGPT
  # Replace escaped bashslashes and dollar signs
  str = str.gsub('\\\\', "\x00").gsub('\\$', "\x01")

  # Expand variables
  str.gsub!(/\$(\w+)\b|\$\{(\w+)\}/) do |match| # Strange that '\b' is necessary
    key = $1 || $2
#   variables[key] || match
    variables[key] || ""
  end

  # Restore escaped characters
  str.gsub("\x00", '\\').gsub("\x01", '$')
end

#expand_variables?(str, variables) ⇒ Boolean

Return true if any of the variables will be expanded

Returns:

  • (Boolean)


30
31
32
33
34
35
36
37
38
39
40
# File 'lib/prick/ext/expand_variables.rb', line 30

def expand_variables?(str, variables)
  # Replace escaped bashslashes and dollar signs
  str = str.gsub('\\\\', "\x00").gsub('\\$', "\x01")

  # Look for expansion
  str.gsub!(/\$(\w+)\b|\$\{(\w+)\}/) do |match| # Strange that '\b' is necessary
    return true if variables.include?($1 || $2)
  end

  return false
end

#has_variables?(str) ⇒ Boolean

Return true if the string contains a variable

Returns:

  • (Boolean)


43
44
45
46
47
# File 'lib/prick/ext/expand_variables.rb', line 43

def has_variables?(str)
  # Replace escaped bashslashes and dollar signs
  str = str.gsub('\\\\', "\x00").gsub('\\$', "\x01")
  !(str =~ /\$[a-zA-Z{]/).nil?
end