Module Boson::Options

  1. lib/boson/options.rb

This module contains the methods used to define the default option types.

Creating Your Own Option Type

Defining your own option type simply requires one method (create_@type) to parse the option value and create the desired object. To create an option type :date, you could create the following create_date method:

# Drop this in ~/.boson/commands/date_option.rb
module Boson::Options::Date
  def create_date(value)
    # value should be mm/dd
    Date.parse(value + "/#{}")
Boson::OptionParser.send :include, Boson::Options::Date

Modify your config to load this new library by default:

- date_option

In a FileLibrary, we could then use this new option:

module Calendar
  #@options :day=>:date
  def appointments(options={})
    # ...
# >> appointments '-d 10/10'   -> {:day=>#<Date: 4910229/2,0,2299161> }

As you can see, a date object is created from the :date option’s value and passed into appointments().

Some additional tips on the create_* method:

  • The argument passed to the method is the option value from the user.
  • To access the current option name use @current_option.
  • To access the hash of attributes the current option has use OptionParser.current_attributes. See for more about option attributes.

There are two optional methods per option type: validate_@type and usage_for_@type i.e. validate_date and usage_for_date. Like create_@type, validate_@type takes the option’s value. If the value validation fails, raise an OptionParser::Error with a proper message. All user-defined option types automatically validate for an option value’s existence. The usage_for_* method takes an option’s name (i.e. —day) and returns a usage string to be wrapped in ’[ ]’. If no usage is defined the default would look like ’[—day=:date]’. Consider using the OptionParser.default_usage helper method for your usage.