2018-10-06 23:10:08 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2016-09-14 20:32:11 +00:00
|
|
|
module ExpandVariables
|
2020-11-12 18:09:26 +00:00
|
|
|
VARIABLES_REGEXP = /\$([a-zA-Z_][a-zA-Z0-9_]*)|\${\g<1>}|%\g<1>%/.freeze
|
|
|
|
|
2016-09-14 20:32:11 +00:00
|
|
|
class << self
|
2016-09-14 21:00:15 +00:00
|
|
|
def expand(value, variables)
|
2020-11-12 18:09:26 +00: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
|
|
|
|
|
2021-01-11 18:10:43 +00:00
|
|
|
def possible_var_reference?(value)
|
|
|
|
return unless value
|
|
|
|
|
|
|
|
%w[$ %].any? { |symbol| value.include?(symbol) }
|
|
|
|
end
|
|
|
|
|
2020-11-12 18:09:26 +00:00
|
|
|
private
|
|
|
|
|
|
|
|
def replace_with(value, variables)
|
2019-08-13 15:03:52 +00:00
|
|
|
variables_hash = nil
|
|
|
|
|
2020-11-12 18:09:26 +00:00
|
|
|
value.gsub(VARIABLES_REGEXP) do
|
2019-08-13 15:03:52 +00:00
|
|
|
variables_hash ||= transform_variables(variables)
|
2020-11-12 18:09:26 +00:00
|
|
|
yield(variables_hash, Regexp.last_match)
|
2019-08-13 15:03:52 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2020-11-12 18:09:26 +00: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 15:03:52 +00:00
|
|
|
|
|
|
|
def transform_variables(variables)
|
|
|
|
# Lazily initialise variables
|
|
|
|
variables = variables.call if variables.is_a?(Proc)
|
|
|
|
|
2016-09-14 20:32:11 +00: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 12:14:55 +00:00
|
|
|
end
|
|
|
|
|
2019-08-13 15:03:52 +00:00
|
|
|
variables
|
2016-09-13 12:14:55 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|