Skip to content

Method Options

hulihanapplications edited this page Aug 31, 2011 · 21 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

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_options :force => false
#=> Creates a boolean option with default value false

method_options :alias => "bar"
#=> Creates a string option with default value "bar"

method_options :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 suppling 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

Or:

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

You can supply as many aliases as you want.

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