Method: Thor::Base::ClassMethods#argument
- Defined in:
- lib/thor/base.rb
#argument(name, options = {}) ⇒ Object
Adds an argument to the class and creates an attr_accessor for it.
Arguments are different from options in several aspects. The first one is how they are parsed from the command line, arguments are retrieved from position:
thor command NAME
Instead of:
thor command --name=NAME
Besides, arguments are used inside your code as an accessor (self.argument), while options are all kept in a hash (self.options).
Finally, arguments cannot have type :default or :boolean but can be optional (supplying :optional => :true or :required => false), although you cannot have a required argument after a non-required argument. If you try it, an error is raised.
Parameters
- name<Symbol>
-
The name of the argument.
- options<Hash>
-
Described below.
Options
:desc - Description for the argument. :required - If the argument is required or not. :optional - If the argument is optional or not. :type - The type of the argument, can be :string, :hash, :array, :numeric. :default - Default value for this argument. It cannot be required and have default values. :banner - String to show on usage notes.
Errors
- ArgumentError
-
Raised if you supply a required argument after a non required one.
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 |
# File 'lib/thor/base.rb', line 261 def argument(name, = {}) is_thor_reserved_word?(name, :argument) no_commands { attr_accessor name } required = if .key?(:optional) ![:optional] elsif .key?(:required) [:required] else [:default].nil? end remove_argument name if required arguments.each do |argument| next if argument.required? raise ArgumentError, "You cannot have #{name.to_s.inspect} as required argument after " \ "the non-required argument #{argument.human_name.inspect}." end end [:required] = required arguments << Thor::Argument.new(name, ) end |