class AsyncStorage::Config

Attributes

config_path[RW]

Path to the YAML file with configs

Private Class Methods

attribute_accessor(field, validator: nil, normalizer: nil, default: nil) click to toggle source
# File lib/async_storage/config.rb, line 11
def attribute_accessor(field, validator: nil, normalizer: nil, default: nil)
  normalizer ||= :"normalize_#{field}"
  validator ||= :"validate_#{field}"

  define_method(field) do
    unless instance_variable_defined?(:"@#{field}")
      fallback = config_from_yaml[field.to_s] || default
      return if fallback.nil?

      send(:"#{field}=", fallback.respond_to?(:call) ? fallback.call : fallback)
    end
    instance_variable_get(:"@#{field}")
  end

  define_method(:"#{field}=") do |value|
    value = send(normalizer, field, value) if respond_to?(normalizer, true)
    send(validator, field, value) if respond_to?(validator, true)

    instance_variable_set(:"@#{field}", value)
  end
end

Public Instance Methods

config_path=(value) click to toggle source
# File lib/async_storage/config.rb, line 50
def config_path=(value)
  @config_from_yaml = nil
  @config_path = value
end

Private Instance Methods

config_from_yaml() click to toggle source
# File lib/async_storage/config.rb, line 97
def config_from_yaml
  @config_from_yaml ||= begin
    config_path ? YAML.load_file(config_path) : {}
  rescue Errno::ENOENT, Errno::ESRCH
    {}
  end
end
normalize_expires_in(_attr, value) click to toggle source
# File lib/async_storage/config.rb, line 90
def normalize_expires_in(_attr, value)
  ttl = value.to_i
  return unless ttl > 0

  ttl
end
normalize_namespace(_attribute, value) click to toggle source
# File lib/async_storage/config.rb, line 74
def normalize_namespace(_attribute, value)
  return value.to_s if value.is_a?(Symbol)

  value
end
normalizer_boolean(_attr, value) click to toggle source
# File lib/async_storage/config.rb, line 57
def normalizer_boolean(_attr, value)
  return true if [1, '1', true, 'true'].include?(value)
  return false if [nil, 0, '0', false, 'false'].include?(value)

  value
end
validate_boolean(attribute, value) click to toggle source
# File lib/async_storage/config.rb, line 64
def validate_boolean(attribute, value)
  return if [true, false].include?(value)

  raise InvalidConfig, format(
    "The value %<value>p for %<attr>s is not valid. It must be a boolean",
    value: value,
    attr: attribute,
  )
end
validate_namespace(attribute, value) click to toggle source
# File lib/async_storage/config.rb, line 80
def validate_namespace(attribute, value)
  return if value.is_a?(String) && !value.empty?

  raise InvalidConfig, format(
    "The %<value>p for %<attr>s is not valid. It can't be blank",
    value: value,
    attr: attribute,
  )
end