2018-10-06 19:10:08 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2016-09-14 16:32:11 -04:00
|
|
|
module ExpandVariables
|
|
|
|
class << self
|
2016-09-14 17:00:15 -04:00
|
|
|
def expand(value, variables)
|
2019-08-13 11:03:52 -04:00
|
|
|
variables_hash = nil
|
|
|
|
|
|
|
|
value.gsub(/\$([a-zA-Z_][a-zA-Z0-9_]*)|\${\g<1>}|%\g<1>%/) do
|
|
|
|
variables_hash ||= transform_variables(variables)
|
|
|
|
variables_hash[$1 || $2]
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
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
|