class ASCM::Reader

Reader represents the base class that configuration classes should inherit in order to read settings from ENV

Public Class Methods

def_setting(name, opts = {}) click to toggle source

Public: Declares a new setting to be loaded from the local environment. It automatically appends the provided prefix (through uses_prefix!) to the provided string and capitalizes it.

name - Name of the setting to be loaded opts - Hash of extra options.

default: used to automatically set a value when it cannot be found
         on the current environment. Defaults to `nil`.
map: Lambda to be called in order to map a value obtained from the
     environment. Won't be called when using a value supplied by
     the `default` key, and will fallback to the `default` value
     in case the Lambda throws an error.

Returns nothing, but defines two new methods on the inheriting class. Methods are based on the provided name. Defines a class method with the provided name and another method named `has_#name?`, that returns true whenever the value of name is not nil. After loading settings, those cannot be changed dynamically during runtime.

# File lib/ascm/reader.rb, line 27
def self.def_setting(name, opts = {})
  string_name = name.to_s.freeze
  env_name = "#{@@prefix.nil? ? '' : "#{@@prefix}_"}#{string_name}".upcase
  default = opts.fetch(:default, nil)
  value = ENV.fetch(env_name, default)

  if opts.key? :map
    begin
      value = opts[:map][value]
    rescue StandardError => ex
      ASCM.logger.error("BaseConfig failed to map key #{name}:")
      ASCM.logger.error(ex)
      ASCM.logger.error("Falling back to default value '#{default}'")
      value = default
    end
  end

  define_singleton_method name do
    value
  end

  define_singleton_method "has_#{name}?" do
    !value.nil?
  end

  if string_name.start_with?('is_')
    define_singleton_method "#{name}?" do
      value
    end
  end
end
uses_prefix!(prefix) click to toggle source

Public: Marks the current configuration as to having a prefix before the declared names on def_setting Reffer to def_setting for further details.

prefix - Prefix used by the configuration keys

Returns nothing

# File lib/ascm/reader.rb, line 66
def self.uses_prefix!(prefix)
  @@prefix = prefix
end