Method Options

Jesse Herrick edited this page Jan 14, 2014 · 15 revisions

Thor allows you to specify options for its tasks, using method_options to supply a hash of options, or method_option to provide more detail about an individual option. You can access these options via the options hash.

Available Options

  • :aliases — A list of aliases for this option. Typically, you would use aliases to provide short versions of the option.
  • :banner — The short description of the option, printed out in the usage description. By default, this is the upcase version of the flag (from=FROM).
  • :default — The default value of this option if it is not provided. An option cannot be both :required and have a :default.
  • :lazy_default — A default that is only passed if the cli option is passed without a value.
  • :desc — A description for the option. When printing out full usage for a command using cli help hello, this description will appear next to the option.
  • :required — Indicates that an option is required
  • :type:string, :hash, :array, :numeric, or :boolean (see below for more details)
  • :enum — A list of allowed values for this option.

Types for method_options

  • :boolean is parsed as --option or --option=true
  • :string is parsed as --option=VALUE
  • :numeric is parsed as --option=N
  • :array is parsed as --option=one two three
  • :hash is parsed as --option=name:string age:integer

Default Values

method_option allows a default value to be given. Example:

method_option :value, :default => "some value"
#=> Creates a string option with a default value of "some value"

You can also specify the default as a value to the option name. Examples:

method_option :force => false
#=> Creates a boolean option with default value false

method_option :aliases => "bar"
#=> Creates an alias 'bar'

method_option :threshold => 3.0
#=> Creates a numeric option with default value 3.0

You can also supply :option => :required to mark an option as required. The type is assumed to be string. If you want a required hash with default values as option, you can use method_option which uses a more declarative style:

method_option :attributes, :type => :hash, :default => {}, :required => true

All arguments can be set to nil (except required arguments), by supplying a no- or skip-variant. For example:

thor app name --no-attributes

In previous versions, aliases for options were created automatically, but now they should be explicit. You can supply aliases in both short and declarative styles:

method_options %w( force -f ) => :boolean


method_option :force, :type => :boolean, :aliases => "-f"

You can supply as many aliases as you want.

Note: Thor follows a convention of one-dash-one-letter options. Thus aliases like "-something" wont be parsed; use either "\--something" or "-s" instead.

NOTE: Type :optional available in Thor 0.9.0 was deprecated. Use :string or :boolean instead.