Sha256: 7f2feaa85f4ff8fb7ac16356d0bc62399b88ffdb7c790e1938f90b2bc22df6aa

Contents?: true

Size: 1.34 KB

Versions: 1

Compression:

Stored size: 1.34 KB

Contents

# coding: utf-8

module Confuse
  # An {Item} is a class for storing a description piece of config.
  class Item
    def initialize(key, opts = {})
      @key = key
      @default, @description = opts.values_at(:default, :description)

      @converter = opts[:converter]
      @type = opts[:type]

      @required = opts.key?(:required) ? opts[:required] : true
    end

    attr_reader :description, :required, :converter

    def convert(value)
      converter.call(value)
    end

    def default(config)
      raise Errors::Undefined.new(@key) if @required && @default.nil?

      @default.respond_to?(:call) ? @default.call(config) : @default
    end

    def to_s
      default = if @default && !@default.respond_to?(:call)
                  "default: #{@default}"
                else
                  ''
                end
      "#{@key}:\t#{description} #{default}"
    end

    def to_hash
      {
        :description => @description,
        :default => @default
      }
    end

    private

    def type
      @type || type_from_default || String
    end

    def type_from_default
      unless @default.nil?
        case @default
        when TrueClass, FalseClass
          :bool
        when Proc
          String
        else
          @default.class
        end
      end
    end

    def converter
      @converter ||= Converter[type]
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
confuse-1.1.1 lib/confuse/item.rb