Class: Slop

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/slop-2.3.1/lib/slop.rb

Defined Under Namespace

Classes: Error, InvalidArgumentError, InvalidOptionError, MissingArgumentError, MissingOptionError, Option, Options

Constant Summary collapse

VERSION =

Returns The current version string.

Returns:

  • (String)

    The current version string

'2.3.1'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Enumerable

#dups

Constructor Details

#initialize(*opts, &block) ⇒ Slop

Returns a new instance of Slop.

Parameters:

  • opts (Hash)

    a customizable set of options

  • options (Hash)

    a customizable set of options

Options Hash (*opts):

  • :help (Boolean)
    • Automatically add the ‘help` option

  • :strict (Boolean)
    • Raises when a non listed option is found, false by default

  • :multiple_switches (Boolean)
    • Allows ‘-abc` to be processed as the options ’a’, ‘b’, ‘c’ and will force their argument values to true. By default Slop with parse this as ‘a’ with the argument ‘bc’

  • :banner (String)
    • The banner text used for the help

  • :on_empty (Proc, #call)
    • Any object that respondes to ‘call` which is executed when Slop has no items to parse

  • :io (IO, #puts) — default: $stderr
    • An IO object for writing to when :help => true is used

  • :exit_on_help (Boolean) — default: true
    • When false and coupled with the :help option, Slop will not exit inside of the ‘help` option

  • :ignore_case (Boolean) — default: false
    • Ignore options case

  • :on_noopts (Proc, #call)
    • Trigger an event when no options are found

  • :autocreate (Boolean) — default: false
    • Autocreate options depending on the Array passed to #parse

  • :arguments (Boolean) — default: false
    • Set to true to enable all specified options to accept arguments by default

  • :aliases (Array) — default: []
    • Primary uses by commands to implement command aliases

  • :completion (Boolean) — default: true
    • When true, commands will be auto completed. Ie ‘foobar` will be executed simply when `foo` `fo` or `foob` are used



389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# File 'lib/slop-2.3.1/lib/slop.rb', line 389

def initialize(*opts, &block)
  sloptions = opts.last.is_a?(Hash) ? opts.pop : {}
  sloptions[:banner] = opts.shift if opts[0].respond_to?(:to_str)
  opts.each { |o| sloptions[o] = true }

  @options = Options.new
  @commands = {}
  @execution_block = nil

  @longest_flag = 0
  @invalid_options = []

  @banner = sloptions[:banner]
  @strict = sloptions[:strict]
  @ignore_case = sloptions[:ignore_case]
  @multiple_switches = sloptions.fetch(:multiple_switches, true)
  @autocreate = sloptions[:autocreate]
  @completion = sloptions.fetch(:completion, true)
  @arguments = sloptions[:arguments]
  @on_empty = sloptions[:on_empty]
  @io = sloptions.fetch(:io, $stderr)
  @on_noopts = sloptions[:on_noopts] || sloptions[:on_optionless]
  @sloptions = sloptions

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

  if sloptions[:help]
    on :h, :help, 'Print this help message', :tail => true do
      @io.puts help
      exit unless sloptions[:exit_on_help] == false
    end
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args, &block) ⇒ Boolean

Allows you to check whether an option was specified in the parsed list

Merely sugar for ‘present?`

Examples:

#== ruby foo.rb -v
opts.verbose? #=> true
opts.name?    #=> false

Returns:

  • (Boolean)

    true if this option is present, false otherwise

See Also:



691
692
693
694
695
696
697
698
699
700
# File 'lib/slop-2.3.1/lib/slop.rb', line 691

def method_missing(meth, *args, &block)
  super unless meth.to_s[-1, 1] == '?'
  present = present? meth.to_s.chomp('?')

  (class << self; self; end).instance_eval do
    define_method(meth) { present }
  end

  present
end

Instance Attribute Details

#aliasesArray

Returns A list of aliases this command uses.

Returns:

  • (Array)

    A list of aliases this command uses



339
340
341
# File 'lib/slop-2.3.1/lib/slop.rb', line 339

def aliases
  @aliases
end

Set or return banner text

Examples:

opts = Slop.parse do
  banner "Usage - ruby foo.rb [arguments]"
end

Parameters:

  • text (String) (defaults to: nil)

    Displayed banner text

Returns:

  • (String)

    The current banner



433
434
435
436
# File 'lib/slop-2.3.1/lib/slop.rb', line 433

def banner(text=nil)
  @banner = text if text
  @banner
end

#commandsHash (readonly)

Returns:



318
319
320
# File 'lib/slop-2.3.1/lib/slop.rb', line 318

def commands
  @commands
end

#description(text = nil) ⇒ String

Set or return the description

Examples:

opts = Slop.parse do
  description "This command does a lot of stuff with other stuff."
end

Parameters:

  • text (String) (defaults to: nil)

    Displayed description text

Returns:

  • (String)

    The current description



459
460
461
462
# File 'lib/slop-2.3.1/lib/slop.rb', line 459

def description(text=nil)
  @description = text if text
  @description
end

#longest_flagInteger

Returns The length of the longest flag slop knows of.

Returns:

  • (Integer)

    The length of the longest flag slop knows of



336
337
338
# File 'lib/slop-2.3.1/lib/slop.rb', line 336

def longest_flag
  @longest_flag
end

#optionsOptions (readonly)

Returns:



315
316
317
# File 'lib/slop-2.3.1/lib/slop.rb', line 315

def options
  @options
end

#summary(text = nil) ⇒ String

Set or return the summary

Examples:

opts = Slop.parse do
  summary "do stuff with more stuff"
end

Parameters:

  • text (String) (defaults to: nil)

    Displayed summary text

Returns:

  • (String)

    The current summary



446
447
448
449
# File 'lib/slop-2.3.1/lib/slop.rb', line 446

def summary(text=nil)
  @summary = text if text
  @summary
end

Class Method Details

.optspec(optspec, *options) ⇒ Slop

Build options from an optspec string

Parameters:

  • optspec (String)

    The option spec string

  • options (Array)

    A list of options to forward to Slop.new

Returns:

  • (Slop)

    A new instance of Slop



295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/slop-2.3.1/lib/slop.rb', line 295

def self.optspec(optspec, *options)
  if optspec[/^--+$/]
    banner, optspec = optspec.split(/^--+$/, 2)
  end

  lines = optspec.split("\n").reject(&:empty?)
  opts  = Slop.new(banner, *options)

  lines.each do |line|
    opt, description = line.split(' ', 2)
    short, long = opt.split(',').map { |s| s.sub(/\A--?/, '') }
    argument = long && long[/\=$/]
    long.sub!(/\=$/, '') if argument
    opts.on short, long, description, argument
  end

  opts
end

.parse(items = ARGV, options = {}, &block) ⇒ Slop

Parses the items from a CLI format into a friendly object

Examples:

Specifying three options to parse:

opts = Slops.parse do
  on :v, :verbose, 'Enable verbose mode'
  on :n, :name,    'Your name'
  on :a, :age,     'Your age'
end

Parameters:

  • items (Array) (defaults to: ARGV)

    Items to parse into options.

Returns:

  • (Slop)

    Returns an instance of Slop



278
279
280
# File 'lib/slop-2.3.1/lib/slop.rb', line 278

def self.parse(items=ARGV, options={}, &block)
  initialize_and_parse items, false, options, &block
end

.parse!(items = ARGV, options = {}, &block) ⇒ Slop

Identical to parse, but removes parsed options from the original Array

Returns:

  • (Slop)

    Returns an instance of Slop



286
287
288
# File 'lib/slop-2.3.1/lib/slop.rb', line 286

def self.parse!(items=ARGV, options={}, &block)
  initialize_and_parse items, true, options, &block
end

Instance Method Details

#[](key) ⇒ Object Also known as: get

Returns the value associated with that option. If an option doesn’t exist, a command will instead be searched for

Examples:

opts[:name] #=> "Emily"
opts.get(:name) #=> "Emily"

Parameters:

  • key (Symbol)

    Option symbol

Returns:

  • (Object)

    Returns the value associated with that option. If an option doesn’t exist, a command will instead be searched for



489
490
491
492
# File 'lib/slop-2.3.1/lib/slop.rb', line 489

def [](key)
  option = @options[key]
  option ? option.argument_value : @commands[key]
end

#command(label, options = {}, &block) ⇒ Slop

Namespace options depending on what command is executed

Examples:

opts = Slop.new do
  command :create do
    on :v, :verbose
  end
end

# ARGV is `create -v`
opts.commands[:create].verbose? #=> true

Parameters:

  • label (Symbol, String)
  • options (Hash) (defaults to: {})

Returns:

  • (Slop)

    a new instance of Slop namespaced to label

Raises:

  • (ArgumentError)

    When this command already exists

Since:

  • 1.5.0



548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
# File 'lib/slop-2.3.1/lib/slop.rb', line 548

def command(label, options={}, &block)
  if @commands.key?(label)
    raise ArgumentError, "command `#{label}` already exists"
  end

  slop = Slop.new @sloptions.merge(options)
  slop.aliases = Array(options.delete(:aliases) || options.delete(:alias))
  @commands[label] = slop

  slop.aliases.each { |a| @commands[a] = @commands[label] }

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

  slop
end

#each(&block) ⇒ Object

Enumerable interface



479
480
481
# File 'lib/slop-2.3.1/lib/slop.rb', line 479

def each(&block)
  @options.each(&block)
end

#execute(args = []) {|Slop| ... } ⇒ Object

Add an execution block (for commands)

Examples:

opts = Slop.new do
  command :foo do
    on :v, :verbose

    execute { |o| p o.verbose? }
  end
end
opts.parse %w[foo --verbose] #=> true

Parameters:

  • args (Array) (defaults to: [])

    The list of arguments to send to this command is invoked

Yields:

  • (Slop)

    an instance of Slop for this command

Since:

  • 1.8.0



610
611
612
613
614
615
616
# File 'lib/slop-2.3.1/lib/slop.rb', line 610

def execute(args=[], &block)
  if block_given?
    @execution_block = block
  elsif @execution_block.respond_to?(:call)
    @execution_block.call(self, args)
  end
end

#inspectString

Returns This Slop object will options and configuration settings revealed.

Returns:

  • (String)

    This Slop object will options and configuration settings revealed



746
747
748
749
# File 'lib/slop-2.3.1/lib/slop.rb', line 746

def inspect
  "#<Slop config_options=#{@sloptions.inspect}\n  " +
  options.map(&:inspect).join("\n  ") + "\n>"
end

#missingArray

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

Examples:

opts = Slop.new do
  on :n, :name, 'Your name', true
  on :p, :password, 'Your password', true
  on :A, 'Use auth?'
end

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

Returns:

  • (Array)

    A list of options missing from the parsed string

Since:

  • 2.1.0



677
678
679
# File 'lib/slop-2.3.1/lib/slop.rb', line 677

def missing
  @options.select { |opt| not present?(opt.key) }.map { |opt| opt.key }
end

#on_empty(obj = nil, &block) ⇒ Object Also known as: on_empty=

Trigger an event when Slop has no values to parse

Examples:

Slop.parse do
  on_empty { puts 'No argument given!' }
end

Parameters:

  • obj (Object, #call) (defaults to: nil)

    The object (which can be anything responding to ‘call`)

Since:

  • 1.5.0



575
576
577
# File 'lib/slop-2.3.1/lib/slop.rb', line 575

def on_empty(obj=nil, &block)
  @on_empty ||= (obj || block)
end

#on_noopts(obj = nil, &block) ⇒ Object Also known as: on_optionless

Trigger an event when the arguments contain no options

Examples:

Slop.parse do
  on_noopts { puts 'No options here!' }
end

Parameters:

  • obj (Object, #call) (defaults to: nil)

    The object to be triggered (anything responding to ‘call`)

Since:

  • 1.6.0



589
590
591
# File 'lib/slop-2.3.1/lib/slop.rb', line 589

def on_noopts(obj=nil, &block)
  @on_noopts ||= (obj || block)
end

#option(*args, &block) ⇒ Slop::Option Also known as: opt, on

Specify an option with a short or long version, description and type

Examples:

opts = Slop.parse do
  on :n, :name, 'Your username', true # Required argument
  on :a, :age,  'Your age (optional)', :optional => true
  on :g, :gender, 'Your gender', :optional => false
  on :V, :verbose, 'Run in verbose mode', :default => true
  on :P, :people, 'Your friends', true, :as => Array
  on :h, :help, 'Print this help screen' do
    puts help
  end
end

Parameters:

  • args (*)

    Option configuration.

Options Hash (*args):

  • :short_flag (Symbol, String)

    Short option name.

  • :long_flag (Symbol, String)

    Full option name.

  • :description (String)

    Option description for use in Slop#help

  • :argument (Boolean)

    Specifies whether this option requires an argument

  • :options (Hash)

    Optional option configurations.

Returns:



516
517
518
519
520
521
522
523
524
525
526
527
528
# File 'lib/slop-2.3.1/lib/slop.rb', line 516

def option(*args, &block)
  options = args.last.is_a?(Hash) ? args.pop : {}

  short, long, desc, arg, extras = clean_options(args)

  options.merge!(extras)
  options[:argument] = true if @sloptions[:all_accept_arguments]

  option = Option.new(self, short, long, desc, arg, options, &block)
  @options << option

  option
end

#parse(items = ARGV, &block) ⇒ Object

Parse a list of options, leaving the original Array unchanged

Parameters:

  • items (Array) (defaults to: ARGV)

    A list of items to parse



467
468
469
# File 'lib/slop-2.3.1/lib/slop.rb', line 467

def parse(items=ARGV, &block)
  parse_items items, &block
end

#parse!(items = ARGV, &block) ⇒ Object

Parse a list of options, removing parsed options from the original Array

Parameters:

  • items (Array) (defaults to: ARGV)

    A list of items to parse



474
475
476
# File 'lib/slop-2.3.1/lib/slop.rb', line 474

def parse!(items=ARGV, &block)
  parse_items items, true, &block
end

#present?(*option_names) ⇒ Boolean

Check if an option is specified in the parsed list

Does the same as Slop#option? but a convenience method for unacceptable method names

Parameters:

  • The (Object)

    object name(s) to check

Returns:

  • (Boolean)

    true if these options are present, false otherwise

Since:

  • 1.5.0



710
711
712
# File 'lib/slop-2.3.1/lib/slop.rb', line 710

def present?(*option_names)
  option_names.all? { |opt| @options[opt] && @options[opt].count > 0 }
end

#to_hash(symbols = true) ⇒ Hash Also known as: to_h

Returns the parsed list into a option/value hash

Examples:

opts.to_hash #=> { :name => 'Emily' }

# strings!
opts.to_hash(false) #=> { 'name' => 'Emily' }

Returns:



626
627
628
629
630
631
632
633
# File 'lib/slop-2.3.1/lib/slop.rb', line 626

def to_hash(symbols=true)
  @options.reduce({}) do |hsh, option|
    key = option.key
    key = key.to_sym if symbols
    hsh[key] = option.argument_value
    hsh
  end
end

#to_sString Also known as: help

Returns the banner followed by available options listed on the next line

Examples:

opts = Slop.parse do
  banner "Usage - ruby foo.rb [arguments]"
  on :v, :verbose, "Enable verbose mode"
end
puts opts

Returns:



723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
# File 'lib/slop-2.3.1/lib/slop.rb', line 723

def to_s
  parts = []

  parts << banner if banner
  parts << summary if summary
  parts << wrap_and_indent(description, 80, 4) if description

  if options.size > 0
    parts << "options:"

    heads = @options.reject(&:tail)
    tails = @options.select(&:tail)
    all = (heads + tails).select(&:help)

    parts << all.map(&:to_s).join("\n")
  end

  parts.join("\n\n")
end

#to_struct(name = nil) ⇒ Class

Return parsed items as a new Class

Examples:

opts = Slop.new do
  on :n, :name, 'Persons name', true
  on :a, :age, 'Persons age', true, :as => :int
  on :s, :sex, 'Persons sex m/f', true, :match => /^[mf]$/
  on :A, :admin, 'Enable admin mode'
end

opts.parse %w[ --name Lee --age 22 -s m --admin ]

person = opts.to_struct("Person")
person.class  #=> Struct::Person
person.name   #=> 'Lee'
person.age    #=> 22
person.sex    #=> m
person.admin  #=> true

Parameters:

  • name (String) (defaults to: nil)

    The name of this class

Returns:

  • (Class)

    The new class, or nil if there are no options

Since:

  • 2.0.0



658
659
660
661
# File 'lib/slop-2.3.1/lib/slop.rb', line 658

def to_struct(name=nil)
  hash = to_hash
  Struct.new(name, *hash.keys).new(*hash.values) unless hash.empty?
end