Method: CommandLine::Option#initialize

Defined in:
lib/commandline/optionparser/option.rb

#initialize(*all) ⇒ Option

Option.new(:flag, :posix => true, :names => %w(–opt))

TODO: Should we test and raise key is not one of :names, opt_description, … This will prevent typos. Can users add properties to an Option that are their own?



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/commandline/optionparser/option.rb', line 65

def initialize(*all)
  @posix = false

  raise(MissingPropertyError,
    "No properties specified for new #{self.class}.") if all.empty?

  until Hash === all[0]
    case (prop = all.shift)
    when :flag then @flag = true
    when :posix then @posix = true
    else 
      raise(InvalidPropertyError, "Unknown option setting '#{prop}'.")
    end
  end

  unknown_keys = all[0].keys.find_all { |k| !PROPERTIES.include?(k) && /^use?r_/ !~ "#{k}" }
  raise(InvalidPropertyError, 
    "The key #{unknown_keys.inspect} is not known and is not a user key.") unless 
      unknown_keys.empty?

  @flag = nil unless defined?(@flag)
  type = @flag.nil? ? :default : :flag
  merge_hash = 
    case type
    when :flag then FLAG_BASE_OPTS
    when :default then DEFAULT_OPTS
    else raise(InvalidConstructionError, 
      "Invalid arguments to Option.new. Must be a property hash with "+
      "keys [:names, :arity, :opt_description, :arg_description, "+
      ":opt_found, :opt_not_found] or "+
      "an option type [:flag, :default].")
    end

  @properties = {}.merge(merge_hash)
  all.each { |properties|
    raise(InvalidPropertyError, 
      "Don't understand argument of type '#{properties.class}' => "+
          "#{properties.inspect} passed to #{self.class}.new. Looking "+
          "for type Hash.") unless properties.kind_of?(Hash)

    @properties.merge!(properties)
  }
  
  @properties[:names] = [@properties[:names]].flatten.compact

  arg_arity = @properties[:arity]
  @properties[:arity] = [arg_arity, arg_arity] unless 
    arg_arity.kind_of?(Array)

  raise "Invalid value for arity '#{arg_arity}'." unless 
    arg_arity.kind_of?(Array) || arg_arity.kind_of?(Fixnum)

  raise(InvalidArgumentArityError,
    "Conflicting value given to new option: :flag "+
    "and :arity = #{@properties[:arity].inspect}.") if 
      :flag == type && [0,0] != @properties[:arity]

  names = @properties[:names]
  raise(MissingOptionNameError, 
    "Attempt to create an Option without :names defined.") if 
    names.nil? || names.empty?

  names.each { |name| check_option_name(name) }
  validate_arity @properties[:arity]

  create_opt_description if :flag == type
end