Class: Roast::Workflow::Interpolator

Inherits:
Object
  • Object
show all
Defined in:
lib/roast/workflow/interpolator.rb

Defined Under Namespace

Classes: NullLogger

Instance Method Summary collapse

Constructor Details

#initialize(context, logger: nil) ⇒ Interpolator

Returns a new instance of Interpolator.



6
7
8
9
# File 'lib/roast/workflow/interpolator.rb', line 6

def initialize(context, logger: nil)
  @context = context
  @logger = logger || NullLogger.new
end

Instance Method Details

#interpolate(text) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/roast/workflow/interpolator.rb', line 11

def interpolate(text)
  return text unless text.is_a?(String) && text.include?("{{") && text.include?("}}")

  # Check if this is a shell command context
  is_shell_command = text.strip.start_with?("$(") && text.strip.end_with?(")")

  # Replace all {{expression}} with their evaluated values
  text.gsub(/\{\{([^}]+)\}\}/) do |match|
    expression = Regexp.last_match(1).strip
    begin
      # Evaluate the expression in the context
      result = @context.instance_eval(expression).to_s

      # Escape shell metacharacters if this is a shell command
      if is_shell_command
        escape_shell_metacharacters(result)
      else
        result
      end
    rescue => e
      # Provide a detailed error message but preserve the original expression
      error_msg = "Error interpolating {{#{expression}}}: #{e.message}. This variable is not defined in the workflow context."
      @logger.error(error_msg)
      match # Preserve the original expression in the string
    end
  end
end