Class: Nero::EnvTag

Inherits:
BaseTag show all
Defined in:
lib/nero/env_tag.rb

Instance Method Summary collapse

Constructor Details

#initialize(coerce: nil, optional: false) ⇒ EnvTag

Returns a new instance of EnvTag.



5
6
7
8
# File 'lib/nero/env_tag.rb', line 5

def initialize(coerce: nil, optional: false)
  @coerce = coerce
  @optional = optional
end

Instance Method Details

#resolve(args, context:) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/nero/env_tag.rb', line 10

def resolve(args, context:)
  var_name = args[0]
  default = args[1]
  raw = context.environ[var_name]

  if raw.nil? && default.nil?
    context.add_error("environment variable #{var_name} is not set") unless @optional
    return nil
  end

  value = raw || default.to_s

  return value unless @coerce

  begin
    @coerce.call(value)
  rescue ArgumentError => e
    context.add_error("cannot coerce #{var_name}=#{value.inspect}: #{e.message}")
    nil
  end
end