Sha256: 3e80fe13152640562fdc2604e816c4d715c80dfeec1b2e9f927a1a701d35fe26

Contents?: true

Size: 1.28 KB

Versions: 7

Compression:

Stored size: 1.28 KB

Contents

module Coco
  module Options
    class Option
      include Options::Item

      attr_accessor :default
      attr_reader :from, :name

      def initialize(name, required: false, value: :undefined, from: nil, **kwargs)
        @name = name.to_sym
        @required = required
        @value = value
        @from = Array(from)
        @private = kwargs.fetch(:private, false)
        @default = kwargs.fetch(:default, nil)
        @alias = kwargs.fetch(:alias, nil)
      end

      def validate_required!
        if required? && undefined?
          raise ArgumentError, "The `#{name}` option requires a value"
        end
      end

      def required?
        @required == true
      end

      def undefined?
        @value == :undefined
      end

      def value
        undefined? ? default : @value
      end

      def value=(val)
        if from.any? && !from.include?(val)
          raise ArgumentError, "`#{val}` is not a valid #{name} value.\n\tAvailable options: #{from}"
        end
        @value = val
      end

      def to_h
        h = {
          name: name,
          alias: @alias,
          required: required?,
          private: private?,
          from: from,
          default: default
        }
        h[:value] = @value unless undefined?
        h
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
coveragebook_components-0.5.6 lib/coco/options/option.rb
coveragebook_components-0.5.5 lib/coco/options/option.rb
coveragebook_components-0.5.4 lib/coco/options/option.rb
coveragebook_components-0.5.3 lib/coco/options/option.rb
coveragebook_components-0.5.2 lib/coco/options/option.rb
coveragebook_components-0.5.1 lib/coco/options/option.rb
coveragebook_components-0.5.0 lib/coco/options/option.rb