Sha256: 84606b8fa7d05a0b727311e980ecc0aa6140ffe78ef4ca26ddf7e09e430185cb

Contents?: true

Size: 1.38 KB

Versions: 31

Compression:

Stored size: 1.38 KB

Contents

# 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
#
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

# Return true if any of the variables will be expanded
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

Version data entries

31 entries across 31 versions & 1 rubygems

Version Path
prick-0.42.1 lib/prick/ext/expand_variables.rb
prick-0.42.0 lib/prick/ext/expand_variables.rb
prick-0.41.0 lib/prick/ext/expand_variables.rb
prick-0.40.3 lib/prick/ext/expand_variables.rb
prick-0.40.2 lib/prick/ext/expand_variables.rb
prick-0.40.1 lib/prick/ext/expand_variables.rb
prick-0.40.0 lib/prick/ext/expand_variables.rb
prick-0.39.13 lib/prick/ext/expand_variables.rb
prick-0.39.12 lib/prick/ext/expand_variables.rb
prick-0.39.11 lib/prick/ext/expand_variables.rb
prick-0.39.10 lib/prick/ext/expand_variables.rb
prick-0.39.9 lib/prick/ext/expand_variables.rb
prick-0.39.8 lib/prick/ext/expand_variables.rb
prick-0.39.7 lib/prick/ext/expand_variables.rb
prick-0.39.6 lib/prick/ext/expand_variables.rb
prick-0.39.5 lib/prick/ext/expand_variables.rb
prick-0.39.4 lib/prick/ext/expand_variables.rb
prick-0.39.3 lib/prick/ext/expand_variables.rb
prick-0.39.2 lib/prick/ext/expand_variables.rb
prick-0.39.1 lib/prick/ext/expand_variables.rb