Sha256: c489e31b961270fc88df36f1fbb78fa965381f8688b59188991c35d7ed72ebb0

Contents?: true

Size: 1.67 KB

Versions: 1

Compression:

Stored size: 1.67 KB

Contents

module Cliprompt

  class OptionException < StandardError
  end

  class Optionset

    attr_reader :choices, :default, :boolean, :envdefault

    def initialize(options = nil)
      @choices = []
      @default = nil
      @boolean = false
      @envdefault = nil
      unless options.nil?
        meth = "parse_#{options.class.name.downcase}".to_sym
        if respond_to? meth
          send(meth, options)
        else
          fail OptionException, "Undefined parser ::#{meth}"
        end
      end
    end

    def parse_hash(args)
      @choices = args[:choices] || args['choices'] || []
      parse_array @choices
      if args[:default] == false || args['default'] == false
        @default ||= false
      else
        @default ||= args[:default] || args['default']
      end
      @boolean = args[:boolean] || args['boolean']
      @default = true if (@boolean && @default.nil?)
      @envdefault = args[:env] || args['env']
    end

    def parse_array(args)
      @choices = args.map do |a|
        if a[0] && a[0] == '='
          @default = a[1..-1]
        else
          a
        end
      end
    end

    def parse_string(arg)
      if arg.downcase.match /^y(es)?(\/)?n(o)?/
        @boolean = true
        if /y(es)?(\/)?N/.match arg
          @default = false
        else
          @default = true
        end
      else
        @default = arg
      end
    end

    def boolean?
      @boolean
    end

    def display
      back = ''
      if @boolean
        back = @default ? "[Y/n]" : "[y/N]"
      else
        if @choices.count > 0
          back += "(#{@choices.join(' / ')})"
        end
        back += "[#{@default}]" if @default
      end
      return back
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
cliprompt-0.0.1 lib/cliprompt/optionset.rb