2018-10-06 19:10:08 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2016-09-14 16:32:11 -04:00
|
|
|
module ExpandVariables
|
2020-11-12 13:09:26 -05:00
|
|
|
VARIABLES_REGEXP = /\$([a-zA-Z_][a-zA-Z0-9_]*)|\${\g<1>}|%\g<1>%/.freeze
|
|
|
|
|
2016-09-14 16:32:11 -04:00
|
|
|
class << self
|
2016-09-14 17:00:15 -04:00
|
|
|
def expand(value, variables)
|
2020-11-12 13:09:26 -05:00
|
|
|
replace_with(value, variables) do |vars_hash, last_match|
|
|
|
|
match_or_blank_value(vars_hash, last_match)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def expand_existing(value, variables)
|
|
|
|
replace_with(value, variables) do |vars_hash, last_match|
|
|
|
|
match_or_original_value(vars_hash, last_match)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def replace_with(value, variables)
|
2019-08-13 11:03:52 -04:00
|
|
|
variables_hash = nil
|
|
|
|
|
2020-11-12 13:09:26 -05:00
|
|
|
value.gsub(VARIABLES_REGEXP) do
|
2019-08-13 11:03:52 -04:00
|
|
|
variables_hash ||= transform_variables(variables)
|
2020-11-12 13:09:26 -05:00
|
|
|
yield(variables_hash, Regexp.last_match)
|
2019-08-13 11:03:52 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2020-11-12 13:09:26 -05:00
|
|
|
def match_or_blank_value(variables, last_match)
|
|
|
|
variables[last_match[1] || last_match[2]]
|
|
|
|
end
|
|
|
|
|
|
|
|
def match_or_original_value(variables, last_match)
|
|
|
|
match_or_blank_value(variables, last_match) || last_match[0]
|
|
|
|
end
|
2019-08-13 11:03:52 -04:00
|
|
|
|
|
|
|
def transform_variables(variables)
|
|
|
|
# Lazily initialise variables
|
|
|
|
variables = variables.call if variables.is_a?(Proc)
|
|
|
|
|
2016-09-14 16:32:11 -04:00
|
|
|
# Convert hash array to variables
|
|
|
|
if variables.is_a?(Array)
|
|
|
|
variables = variables.reduce({}) do |hash, variable|
|
|
|
|
hash[variable[:key]] = variable[:value]
|
|
|
|
hash
|
|
|
|
end
|
2016-09-13 08:14:55 -04:00
|
|
|
end
|
|
|
|
|
2019-08-13 11:03:52 -04:00
|
|
|
variables
|
2016-09-13 08:14:55 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|