Class: Nero::EnvTag

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

Overview

Requires an env-var to be available and coerces the value. When tag-name ends with "?", the env-var is optional.

Given config:

config.add_tag("env/upcase", klass: Nero::EnvTag[coerce: :upcase])
config.add_tag("env/upcase?", klass: Nero::EnvTag[coerce: :upcase])

Then YAML => result:

"--- env/upcase [MSG, Hello World]" #=> "HELLO WORLD"
"--- env/upcase MSG" #=> raises when not ENV.has_key? "MSG"
"--- env/upcase? MSG" #=> nil

YAML-args supported:

  • scalar — name of env-var, e.g. !env HOME
  • seq — name of env-var and fallback, e.g. !env [HOME, /root]

Options:

  • coerce — symbol or proc to be applied to value of env-var. when using coerce, the block is ignored.

Instance Attribute Summary

Attributes inherited from BaseTag

#coder, #ctx, #options

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from BaseTag

[], #args, #config, #init, #init_ctx, #tag_name

Methods included from Resolvable

#deep_resolve, #resolve_nested!, #try_resolve

Class Method Details

.coerce_bool(v) ⇒ Object



322
323
324
325
326
327
328
329
330
331
332
333
334
335
# File 'lib/nero.rb', line 322

def self.coerce_bool(v)
  return false unless v

  re_true = /y|Y|yes|Yes|YES|true|True|TRUE|on|On|ON/
  re_false = /n|N|no|No|NO|false|False|FALSE|off|Off|OFF/

  case v
  when TrueClass, FalseClass then v
  when re_true then true
  when re_false then false
  else
    raise "bool value should be one of y(es)/n(o), on/off, true/false (got #{v.inspect})"
  end
end

.env_value(k, fallback = nil, optional: false) ⇒ Object



314
315
316
317
318
319
320
# File 'lib/nero.rb', line 314

def self.env_value(k, fallback = nil, optional: false)
  if fallback.nil? && !optional
    ENV.fetch(k)
  else
    ENV.fetch(k, fallback)
  end
end

Instance Method Details

#coercerObject



291
292
293
294
295
296
297
298
299
# File 'lib/nero.rb', line 291

def coercer
  return unless @coerce

  @coercer ||= case @coerce
  when Symbol then @coerce.to_proc
  else
    @coerce
  end
end

#env_valueObject



310
311
312
# File 'lib/nero.rb', line 310

def env_value
  self.class.env_value(*args, optional:)
end

#init_options(coerce: nil) ⇒ Object



301
302
303
# File 'lib/nero.rb', line 301

def init_options(coerce: nil)
  @coerce = coerce
end

#optionalObject Also known as: optional?



305
306
307
# File 'lib/nero.rb', line 305

def optional
  tag_name.end_with?("?") || !!ENV["NERO_ENV_ALL_OPTIONAL"]
end

#resolveObject



281
282
283
284
285
286
287
288
289
# File 'lib/nero.rb', line 281

def resolve(**)
  if coercer
    coercer.call(env_value) unless env_value.nil?
  elsif ctx.dig(:tags, tag_name, :block)
    super
  else
    env_value
  end
end