summaryrefslogtreecommitdiff
path: root/lib/expand_variables.rb
blob: 45af30f46dcbd160ad62bab6e85939fd34b50ae1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 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