Class: Nocode::Util::StringTemplate

Inherits:
Object
  • Object
show all
Defined in:
lib/nocode/util/string_template.rb

Overview

Takes in an expression and interpolates in any parameters using << >> notation. For example:

input = { 'person' => 'hops' }
Nocode::Util::StringTemplate.new("Hello, << person.name >>!").evaluate(input)

Should produce: “Hello, hops!”

Constant Summary collapse

LEFT_TOKEN =
'<<'
RIGHT_TOKEN =
'>>'
SEPARATOR =
'.'
REG_EXPR =
/#{Regexp.quote(LEFT_TOKEN)}(.*?)#{Regexp.quote(RIGHT_TOKEN)}/.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(expression) ⇒ StringTemplate

Returns a new instance of StringTemplate.



18
19
20
21
22
# File 'lib/nocode/util/string_template.rb', line 18

def initialize(expression)
  @expression = expression.to_s

  freeze
end

Instance Attribute Details

#expressionObject (readonly)

Returns the value of attribute expression.



16
17
18
# File 'lib/nocode/util/string_template.rb', line 16

def expression
  @expression
end

Instance Method Details

#evaluate(values = {}) ⇒ Object



24
25
26
27
28
29
30
# File 'lib/nocode/util/string_template.rb', line 24

def evaluate(values = {})
  resolved = tokens_to_values(tokens, values)

  tokens.inject(expression) do |memo, token|
    memo.gsub("#{LEFT_TOKEN}#{token}#{RIGHT_TOKEN}", resolved[token].to_s)
  end
end