gitlab-org--gitlab-foss/lib/expand_variables.rb
Kamil Trzciński 6150c3ff0d Expand variables only when needed
This makes us to expand variables only when needed,
instead of requesting all variables each time.

This specifically helps in situation when explicit name
of `environment: production` is used.
2019-08-13 21:51:29 +02:00

31 lines
711 B
Ruby

# frozen_string_literal: true
module ExpandVariables
class << self
def expand(value, variables)
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)
# Convert hash array to variables
if variables.is_a?(Array)
variables = variables.reduce({}) do |hash, variable|
hash[variable[:key]] = variable[:value]
hash
end
end
variables
end
end
end