Method: Optimist::Option.create

Defined in:
lib/optimist.rb

.create(name, desc = "", opts = {}, settings = {}) ⇒ Object

Determines which type of object to create based on arguments passed to Optimist::opt. This is trickier in Optimist, than other cmdline parsers (e.g. Slop) because we allow the default: to be able to set the option’s type.

Raises:

  • (ArgumentError)


926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
# File 'lib/optimist.rb', line 926

def self.create(name, desc="", opts={}, settings={})

  opttype = Optimist::Parser.registry_getopttype(opts[:type])
  opttype_from_default = get_klass_from_default(opts, opttype)

  raise ArgumentError, ":type specification and default type don't match (default type is #{opttype_from_default.class})" if opttype && opttype_from_default && (opttype.class != opttype_from_default.class)

  opt_inst = (opttype || opttype_from_default || Optimist::BooleanOption.new)

  ## fill in :long
  opt_inst.long.set(name, opts[:long], opts[:alt])

  ## fill in :short
  opt_inst.short.add opts[:short]

  ## fill in :multi
  multi_given = opts[:multi] || false
  opt_inst.multi_given = multi_given

  ## fill in :default for flags
  defvalue = opts[:default] || opt_inst.default

  ## fill in permitted values
  permitted = opts[:permitted] || nil

  ## autobox :default for :multi (multi-occurrence) arguments
  defvalue = [defvalue] if defvalue && multi_given && !defvalue.kind_of?(Array)
  opt_inst.permitted = permitted
  opt_inst.permitted_response = opts[:permitted_response] if opts[:permitted_response]
  opt_inst.default = defvalue
  opt_inst.name = name
  opt_inst.opts = opts
  opt_inst
end