Sha256: 1a39701a0f1c0548bf3ddb10407d0a3fbb6cf8d4b485cfdadd68c0ab85aa1b47

Contents?: true

Size: 1.28 KB

Versions: 3

Compression:

Stored size: 1.28 KB

Contents

# frozen_string_literal: true

# helpers module to DRY out config fetches with optional default
#
# - iterates through args looking for first symbol that is present.
# - non-symbols are treated as literals instead of lookups (so only one matters)
# - raises an error if value is present but not valid for type (Integer or Float)
# - raises an error if value is missing and no default specified
# - if supplied, default must either be valid for type or nil
module ConfigHelper
  def get_x!(*args)
    while args.length.positive?
      k = args.shift
      if k.is_a? Symbol
        k = k.to_s
        return yield(self[k]) if key? k
      else
        raise 'default not last argument' unless args.empty?
        return nil if k.nil?
        return yield(k)
      end
    end
    raise 'value not found'
  end

  def get_i!(*args)
    get_x!(*args) { |v| Integer(v) }
  end

  def get_f!(*args)
    get_x!(*args) { |v| Float(v) }
  end

  def get_s!(*args)
    get_x!(*args, &:to_s)
  end

  def get_b!(*args)
    get_x!(*args) do |v|
      return v if [true, false].include?(v)
      raise ArgumentError, 'not a bool or string' unless v.is_a? String
      case v.downcase
      when 'true'  then true
      when 'false' then false
      else raise ArgumentError, 'not true or false'
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
svcbase-0.1.18 lib/svcbase/config/config_helper.rb
svcbase-0.1.17 lib/svcbase/config/config_helper.rb
svcbase-0.1.16 lib/svcbase/config/config_helper.rb