Class: ERBResolve

Inherits:
Object
  • Object
show all
Defined in:
lib/nub/core.rb

Instance Method Summary collapse

Constructor Details

#initialize(vars) ⇒ ERBResolve

Resolve variables for the given data type

Parameters:

  • vars (Hash/OpenStruct)

    hash or OpenStruct of ERB variables to use

Raises:

  • (ArgumentError)


55
56
57
58
59
60
# File 'lib/nub/core.rb', line 55

def initialize(vars)
  raise ArgumentError.new("Variables are required") if not vars

  @vars = vars.is_a?(OpenStruct) ? vars.to_h : vars
  @context = ERBContext.new(@vars).get_binding
end

Instance Method Details

#resolve(data) ⇒ Object

Resolve variables for the given data type



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/nub/core.rb', line 65

def resolve(data)

  # Recurse
  if data.is_a?(Array)
    data = data.map{|x| resolve(x)}
  elsif data.is_a?(Hash)
    data.each{|k,v| data[k] = resolve(v)}
  end

  # Base case
  if data.is_a?(String)
    data = ERB.new(data).result(@context)
  end

  return data
end

#resolve!(data) ⇒ Object

Resolve variables for the given data type, changes are done inplace



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/nub/core.rb', line 84

def resolve!(data)

  # Recurse
  if data.is_a?(Array)
    for i in 0...data.size
      resolve!(data[i])
    end
  elsif data.is_a?(Hash)
    data.each{|k,v| data[k] = resolve!(v)}
  end

  # Base case
  if data.is_a?(String)
    data.gsub!(data, ERB.new(data).result(@context))
  end

  return data
end