Class: Consult::Template

Inherits:
Object
  • Object
show all
Includes:
TemplateFunctions, Utilities
Defined in:
lib/consult/template.rb

Constant Summary collapse

LOCATIONS =
%i[path paths consul_key consul_keys]

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from TemplateFunctions

#indent, #key, #query, #query_nodes, #secret, #secrets, #service, #timestamp, #with

Methods included from Utilities

#resolve

Constructor Details

#initialize(name, config) ⇒ Template

Returns a new instance of Template.



14
15
16
17
# File 'lib/consult/template.rb', line 14

def initialize(name, config)
  @name = name
  @config = config
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



12
13
14
# File 'lib/consult/template.rb', line 12

def config
  @config
end

#nameObject (readonly)

Returns the value of attribute name.



12
13
14
# File 'lib/consult/template.rb', line 12

def name
  @name
end

Instance Method Details

#destObject



44
45
46
# File 'lib/consult/template.rb', line 44

def dest
  resolve @config.fetch(:dest)
end

#expired?Boolean

Returns:

  • (Boolean)


52
53
54
55
56
# File 'lib/consult/template.rb', line 52

def expired?
  # Treat renders as expired if a TTL isn't set, or it has never been rendered before
  return true if !config.key?(:ttl) || !dest.exist?
  dest.mtime < (Time.now - @config[:ttl].to_i)
end

#ordered_locationsObject



58
59
60
# File 'lib/consult/template.rb', line 58

def ordered_locations
  @config.keys & LOCATIONS
end

#pathObject



32
33
34
# File 'lib/consult/template.rb', line 32

def path
  resolve @config[:path]
end

#pathsObject



36
37
38
# File 'lib/consult/template.rb', line 36

def paths
  @config.fetch(:paths, []).map { |path| resolve(path) }
end

#render(save: true) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/consult/template.rb', line 19

def render(save: true)
  # Attempt to render
  renderer = ERB.new(contents, nil, '-')
  result = renderer.result(binding)

  File.open(dest, 'w') { |f| f << result } if save
  result
rescue StandardError => e
  STDERR.puts "Error rendering template: #{name}"
  STDERR.puts e
  nil
end

#should_render?Boolean

Returns:

  • (Boolean)


48
49
50
# File 'lib/consult/template.rb', line 48

def should_render?
  expired?
end

#varsObject



40
41
42
# File 'lib/consult/template.rb', line 40

def vars
  @config[:vars]
end