Class: Slop

### Home Classes Methods

### In Files

- lib/slop.rb
- lib/slop/commands.rb
- lib/slop/option.rb

### Parent

Object

### Namespace

- CLASS Slop::Commands
- CLASS Slop::Error
- CLASS Slop::InvalidArgumentError
- CLASS Slop::InvalidCommandError
- CLASS Slop::InvalidOptionError
- CLASS Slop::MissingArgumentError
- CLASS Slop::MissingOptionError
- CLASS Slop::Option

### Methods

- ::new
- ::optspec
- ::parse
- ::parse!
- #[]
- #add_callback
- #banner
- #banner=
- #command
- #description
- #description=
- #each
- #fetch_command
- #fetch_option
- #get
- #help
- #missing
- #on
- #opt
- #option
- #parse
- #parse!
- #present?
- #respond_to_missing?
- #run
- #separator
- #strict?
- #to_h
- #to_hash
- #to_s

### Included Modules

- Enumerable

### Class/Module Index

Quicksearch

- Slop
- Slop::Commands
- Slop::Error
- Slop::InvalidArgumentError
- Slop::InvalidCommandError
- Slop::InvalidOptionError
- Slop::MissingArgumentError
- Slop::MissingOptionError
- Slop::Option

No matching classes.

# Slop

### Constants

DEFAULT_OPTIONS

  Returns a default Hash of configuration options this Slop instance uses.

VERSION

### Attributes

commands[R]

The Hash of sub-commands for this Slop instance.

config[R]

The Hash of configuration options for this Slop instance.

options[R]

The Array of Slop::Option objects tied to this Slop instance.

### Public Class Methods

new(config = {}, &block) click to toggle source

Create a new instance of Slop and optionally build options via a block.

config - A Hash of configuration options. block - An optional block used to specify options.

    # File lib/slop.rb, line 128
    def initialize(config = {}, &block)
      @config = DEFAULT_OPTIONS.merge(config)
      @options = []
      @commands = {}
      @trash = []
      @triggered_options = []
      @unknown_options = []
      @callbacks = {}
      @separators = {}
      @runner = nil
      @command = config.delete(:command)

      if block_given?
        block.arity == 1 ? yield(self) : instance_eval(&block)
      end

      if config[:help]
        on('-h', '--help', 'Display this help message.', :tail => true) do
          puts help
          exit
        end
      end
    end

optspec(string, config = {}) click to toggle source

Build a Slop object from a option specification.

This allows you to design your options via a simple String rather than programatically. Do note though that with this method, you're unable to pass any advanced options to the on() method when creating options.

string - The optspec String config - A Hash of configuration options to pass to Slop.new

Examples:

    opts = Slop.optspec(<<-SPEC)
    ruby foo.rb [options]
    ---
    n,name=     Your name
    a,age=      Your age
    A,auth      Sign in with auth
    p,passcode= Your secret pass code
    SPEC

    opts.fetch_option(:name).description #=> "Your name"

Returns a new instance of Slop.

    # File lib/slop.rb, line 93
    def optspec(string, config = {})
      warn "[DEPRECATED] `Slop.optspec` is deprecated and will be removed in version 4"
      config[:banner], optspec = string.split(/^--+$/, 2) if string[/^--+$/]
      lines = optspec.split("\n").reject(&:empty?)
      opts  = Slop.new(config)

      lines.each do |line|
        opt, description = line.split(' ', 2)
        short, long = opt.split(',').map { |s| s.sub(/\A--?/, '') }
        opt = opts.on(short, long, description)

        if long && long.end_with?('=')
          long.sub!(/\=$/, '')
          opt.config[:argument] = true
        end
      end

      opts
    end

parse(items = ARGV, config = {}, &block) click to toggle source

items - The Array of items to extract options from (default: ARGV). config - The Hash of configuration options to send to Slop.new(). block - An optional block used to add options.

Examples:

    Slop.parse(ARGV, :help => true) do
      on '-n', '--name', 'Your username', :argument => true
    end

Returns a new instance of Slop.

    # File lib/slop.rb, line 53
    def parse(items = ARGV, config = {}, &block)
      parse! items.dup, config, &block
    end

parse!(items = ARGV, config = {}, &block) click to toggle source

items - The Array of items to extract options from (default: ARGV). config - The Hash of configuration options to send to Slop.new(). block - An optional block used to add options.

Returns a new instance of Slop.

    # File lib/slop.rb, line 62
    def parse!(items = ARGV, config = {}, &block)
      config, items = items, ARGV if items.is_a?(Hash) && config.empty?
      slop = new config, &block
      slop.parse! items
      slop
    end

### Public Instance Methods

[](key) click to toggle source

Fetch an options argument value.

key - The Symbol or String option short or long flag.

Returns the Object value for this option, or nil.

    # File lib/slop.rb, line 293
    def [](key)
      option = fetch_option(key)
      option.value if option
    end

Also aliased as: get
add_callback(label, &block) click to toggle source

Add a callback.

label - The Symbol identifier to attach this callback.

Returns nothing.

    # File lib/slop.rb, line 413
    def add_callback(label, &block)
      (@callbacks[label] ||= []) << block
    end

banner(banner = nil) click to toggle source

Get or set the banner.

banner - The String to set the banner.

Returns the banner String.

    # File lib/slop.rb, line 171
    def banner(banner = nil)
      config[:banner] = banner if banner
      config[:banner]
    end

banner=(banner) click to toggle source

Set the banner.

banner - The String to set the banner.

    # File lib/slop.rb, line 162
    def banner=(banner)
      config[:banner] = banner
    end

command(command, options = {}, &block) click to toggle source

Add a new command.

command - The Symbol or String used to identify this command. options - A Hash of configuration options (see Slop::new)

Returns a new instance of Slop mapped to this command.

    # File lib/slop.rb, line 199
    def command(command, options = {}, &block)
      options = @config.merge(options)
      @commands[command.to_s] = Slop.new(options.merge(:command => command.to_s), &block)
    end

description(desc = nil) click to toggle source

Get or set the description (used for commands).

desc - The String to set the description.

Returns the description String.

    # File lib/slop.rb, line 188
    def description(desc = nil)
      config[:description] = desc if desc
      config[:description]
    end

description=(desc) click to toggle source

Set the description (used for commands).

desc - The String to set the description.

    # File lib/slop.rb, line 179
    def description=(desc)
      config[:description] = desc
    end

each(&block) click to toggle source

Enumerable interface. Yields each Slop::Option.

    # File lib/slop.rb, line 312
    def each(&block)
      options.each(&block)
    end

fetch_command(command) click to toggle source

Fetch a Slop object associated with this command.

command - The String or Symbol name of the command.

Examples:

    opts.command :foo do
      on :v, :verbose, 'Enable verbose mode'
    end

    # ruby run.rb foo -v
    opts.fetch_command(:foo).verbose? #=> true

    # File lib/slop.rb, line 404
    def fetch_command(command)
      @commands[command.to_s]
    end

fetch_option(key) click to toggle source

Fetch a Slop::Option object.

key - The Symbol or String option key.

Examples:

    opts.on(:foo, 'Something fooey', :argument => :optional)
    opt = opts.fetch_option(:foo)
    opt.class #=> Slop::Option
    opt.accepts_optional_argument? #=> true

Returns an Option or nil if none were found.

    # File lib/slop.rb, line 388
    def fetch_option(key)
      options.find { |option| [option.long, option.short].include?(clean(key)) }
    end

get(key) click to toggle source
Alias for: []
help() click to toggle source
Alias for: to_s
missing() click to toggle source

Fetch a list of options which were missing from the parsed list.

Examples:

    opts = Slop.new do
      on :n, :name=
      on :p, :password=
    end

    opts.parse %w[ --name Lee ]
    opts.missing #=> ['password']

Returns an Array of Strings representing missing options.

    # File lib/slop.rb, line 372
    def missing
      (options - @triggered_options).map(&:key)
    end

on(*objects, &block) click to toggle source

Add an Option.

objects - An Array with an optional Hash as the last element.

Examples:

    on '-u', '--username=', 'Your username'
    on :v, :verbose, 'Enable verbose mode'

Returns the created instance of Slop::Option.

    # File lib/slop.rb, line 276
    def on(*objects, &block)
      option = build_option(objects, &block)
      original = options.find do |o|
        o.long and o.long == option.long or o.short and o.short == option.short
      end
      options.delete(original) if original
      options << option
      option
    end

Also aliased as: option, opt
opt(*objects, &block) click to toggle source
Alias for: on
option(*objects, &block) click to toggle source
Alias for: on
parse(items = ARGV, &block) click to toggle source

Parse a list of items, executing and gathering options along the way.

items - The Array of items to extract options from (default: ARGV). block - An optional block which when used will yield non options.

Returns an Array of original items.

    # File lib/slop.rb, line 210
    def parse(items = ARGV, &block)
      parse! items.dup, &block
      items
    end

parse!(items = ARGV, &block) click to toggle source

Parse a list of items, executing and gathering options along the way. unlike parse() this method will remove any options and option arguments from the original Array.

items - The Array of items to extract options from (default: ARGV). block - An optional block which when used will yield non options.

Returns an Array of original items with options removed.

    # File lib/slop.rb, line 223
    def parse!(items = ARGV, &block)
      if items.empty? && @callbacks[:empty]
        @callbacks[:empty].each { |cb| cb.call(self) }
        return items
      end

      # reset the trash so it doesn't carry over if you parse multiple
      # times with the same instance
      @trash.clear

      if cmd = @commands[items[0]]
        items.shift
        return cmd.parse! items
      end

      items.each_with_index do |item, index|
        @trash << index && break if item == '--'
        autocreate(items, index) if config[:autocreate]
        process_item(items, index, &block) unless @trash.include?(index)
      end
      items.reject!.with_index { |item, index| @trash.include?(index) }

      missing_options = options.select { |opt| opt.required? && opt.count < 1 }
      if missing_options.any?
        raise MissingOptionError,
        "Missing required option(s): #{missing_options.map(&:key).join(', ')}"
      end

      if @unknown_options.any?
        raise InvalidOptionError, "Unknown options #{@unknown_options.join(', ')}"
      end

      if @triggered_options.empty? && @callbacks[:no_options]
        @callbacks[:no_options].each { |cb| cb.call(self) }
      end

      if @runner.respond_to?(:call)
        @runner.call(self, items) unless config[:help] and present?(:help)
      end

      items
    end

present?(*keys) click to toggle source

Check for an options presence.

Examples:

    opts.parse %w( --foo )
    opts.present?(:foo) #=> true
    opts.present?(:bar) #=> false

Returns true if all of the keys are present in the parsed arguments.

    # File lib/slop.rb, line 348
    def present?(*keys)
      keys.all? { |key| (opt = fetch_option(key)) && opt.count > 0 }
    end

respond_to_missing?(method_name, include_private = false) click to toggle source

Override this method so we can check if an option? method exists.

Returns true if this option key exists in our list of options.

    # File lib/slop.rb, line 355
    def respond_to_missing?(method_name, include_private = false)
      options.any? { |o| o.key == method_name.to_s.chop } || super
    end

run(callable = nil, &block) click to toggle source

Specify code to be executed when these options are parsed.

callable - An object responding to a call method.

yields - The instance of Slop parsing these options

    An Array of unparsed arguments

Example:

    Slop.parse do
      on :v, :verbose

      run do |opts, args|
        puts "Arguments: #{args.inspect}" if opts.verbose?
      end
    end

    # File lib/slop.rb, line 332
    def run(callable = nil, &block)
      @runner = callable || block
      unless @runner.respond_to?(:call)
        raise ArgumentError, "You must specify a callable object or a block to #run"
      end
    end

separator(text) click to toggle source

Add string separators between options.

text - The String text to print.

    # File lib/slop.rb, line 420
    def separator(text)
      if @separators[options.size]
        @separators[options.size] << "\n#{text}"
      else
        @separators[options.size] = text
      end
    end

strict?() click to toggle source

Is strict mode enabled?

Returns true if strict mode is enabled, false otherwise.

    # File lib/slop.rb, line 155
    def strict?
      config[:strict]
    end

to_h(include_commands = false) click to toggle source
Alias for: to_hash
to_hash(include_commands = false) click to toggle source

Returns a new Hash with option flags as keys and option values as values.

include_commands - If true, merge options from all sub-commands.

    # File lib/slop.rb, line 302
    def to_hash(include_commands = false)
      hash = Hash[options.map { |opt| [opt.key.to_sym, opt.value] }]
      if include_commands
        @commands.each { |cmd, opts| hash.merge!(cmd.to_sym => opts.to_hash) }
      end
      hash
    end

Also aliased as: to_h
to_s() click to toggle source

Print a handy Slop help string.

Returns the banner followed by available option help strings.

    # File lib/slop.rb, line 431
    def to_s
      heads  = options.reject(&:tail?)
      tails  = (options - heads)
      opts = (heads + tails).select(&:help).map(&:to_s)
      optstr = opts.each_with_index.map { |o, i|
        (str = @separators[i + 1]) ? [o, str].join("\n") : o
      }.join("\n")

      if @commands.any?
        optstr << "\n" if !optstr.empty?
        optstr << "\nAvailable commands:\n\n"
        optstr << commands_to_help
        optstr << "\n\nSee `<command> --help` for more information on a specific command."
      end

      banner = config[:banner]
      if banner.nil?
        banner = "Usage: #{File.basename($0, '.*')}"
        banner << " #{@command}" if @command
        banner << " [command]" if @commands.any?
        banner << " [options]"
      end
      if banner
        "#{banner}\n#{@separators[0] ? "#{@separators[0]}\n" : ''}#{optstr}"
      else
        optstr
      end
    end

Also aliased as: help

[Validate]

Generated with the Darkfish Rdoc Generator 2.