class Environmentor::Attribute

Constants

Absent

Attributes

default[R]
description[R]
name[R]
namespace_chain[R]
required[R]
required?[R]
type[R]
type_coercer[RW]

Public Class Methods

new(name, namespace_chain, type: :string, required: true, default: Absent, description: nil, help: nil, mappers: {}) click to toggle source
# File lib/environmentor/attribute.rb, line 50
def initialize(name, namespace_chain, type: :string, required: true, default: Absent, description: nil, help: nil, mappers: {})
  raise ArgumentError, "#{type.inspect} isn't a valid type" unless type_coercer.valid_type?(type)
  @name = name
  @namespace_chain = namespace_chain
  @type = type
  @required = required
  @default = default
  @description = description || help
  @mappers_opts = mappers
end

Protected Class Methods

type_coercer() click to toggle source
# File lib/environmentor/attribute.rb, line 114
def self.type_coercer
  Environmentor::TypeCoercer
end

Public Instance Methods

clear_cache!() click to toggle source
# File lib/environmentor/attribute.rb, line 108
def clear_cache!
  remove_instance_variable(:@value)
end
full_name() click to toggle source
# File lib/environmentor/attribute.rb, line 63
def full_name
  (namespace_chain.map(&:name).compact << name).join('.')
end
get_from_mapper(mapper, **opts) click to toggle source
# File lib/environmentor/attribute.rb, line 88
def get_from_mapper(mapper, **opts)
  str_value = mapper.value_for_attribute(self, **opts) or return nil
  type_coercer.coerce_to(type, str_value)
end
get_from_mappers(mappers) click to toggle source
# File lib/environmentor/attribute.rb, line 67
def get_from_mappers(mappers)
  return @value if defined?(@value)

  mappers.each do |mapper|
    begin
      @value = get_from_mapper(
        mapper, **mapper.class.opts_from_mappers_hash(@mappers_opts))
    rescue Environmentor::Mappers::ValueNotFound
      next
    else
      return @value
    end
  end

  return default unless Absent.equal?(default)
  if required?
    raise ValidationError::Missing.new(self, mappers, @mappers_opts)
  end
  nil
end
validate_in_mappers(mappers) click to toggle source
# File lib/environmentor/attribute.rb, line 93
def validate_in_mappers(mappers)
  ValidationErrors.new.tap do |out|
    if required?
      begin
        get_from_mappers(mappers)
      rescue ValidationError => e
        out << e
      rescue StandardError => e
        out << ValidationError.new(self, mappers, @mappers_opts,
                                   message: e.message)
      end
    end
  end
end