2018-12-13 13:39:08 +05:30
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2016-09-29 09:46:39 +05:30
|
|
|
module ExpandVariables
|
2021-01-29 00:20:46 +05:30
|
|
|
VARIABLES_REGEXP = /\$([a-zA-Z_][a-zA-Z0-9_]*)|\${\g<1>}|%\g<1>%/.freeze
|
|
|
|
|
2016-09-29 09:46:39 +05:30
|
|
|
class << self
|
|
|
|
def expand(value, variables)
|
2021-01-29 00:20:46 +05:30
|
|
|
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-10-12 21:52:04 +05:30
|
|
|
variables_hash = nil
|
|
|
|
|
2021-01-29 00:20:46 +05:30
|
|
|
value.gsub(VARIABLES_REGEXP) do
|
2019-10-12 21:52:04 +05:30
|
|
|
variables_hash ||= transform_variables(variables)
|
2021-01-29 00:20:46 +05:30
|
|
|
yield(variables_hash, Regexp.last_match)
|
2019-10-12 21:52:04 +05:30
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2021-01-29 00:20:46 +05:30
|
|
|
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-10-12 21:52:04 +05:30
|
|
|
|
|
|
|
def transform_variables(variables)
|
|
|
|
# Lazily initialise variables
|
|
|
|
variables = variables.call if variables.is_a?(Proc)
|
|
|
|
|
2016-09-29 09:46:39 +05:30
|
|
|
# Convert hash array to variables
|
|
|
|
if variables.is_a?(Array)
|
|
|
|
variables = variables.reduce({}) do |hash, variable|
|
|
|
|
hash[variable[:key]] = variable[:value]
|
|
|
|
hash
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2019-10-12 21:52:04 +05:30
|
|
|
variables
|
2016-09-29 09:46:39 +05:30
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|