Class: Slop

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/slop.rb,
lib/slop/option.rb,
lib/slop/options.rb

Defined Under Namespace

Classes: InvalidArgumentError, InvalidOptionError, MissingArgumentError, Option, Options

Constant Summary collapse

VERSION =

Returns The current version string.

Returns:

  • (String)

    The current version string

'1.5.2'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*opts, &block) ⇒ Slop

Returns a new instance of Slop.

Parameters:

  • options (Hash)
  • opts (Hash)

    a customizable set of options

Options Hash (*opts):

  • :help (Boolean)

    Automatically add the help option

  • :strict (Boolean)

    Strict mode 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



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/slop.rb', line 68

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

  @options = Options.new
  @commands = {}

  @longest_flag = 0
  @invalid_options = []

  @banner ||= sloptions[:banner]
  @strict = sloptions[:strict]
  @multiple_switches = sloptions[:multiple_switches]
  @on_empty = sloptions[:on_empty]
  @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
      puts help
      exit
    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.

Examples:

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

Returns:

  • (Boolean)

    Whether the desired option was specified.



239
240
241
242
# File 'lib/slop.rb', line 239

def method_missing(meth, *args, &block)
  super unless meth.to_s =~ /\?\z/
  !!self[meth.to_s.chomp '?']
end

Instance Attribute Details

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)

    Returns current banner.



106
107
108
109
# File 'lib/slop.rb', line 106

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

#commandsHash (readonly)

Returns:

  • (Hash)


48
49
50
# File 'lib/slop.rb', line 48

def commands
  @commands
end

#longest_flagInteger

Returns The length of the longest flag slop knows of.

Returns:

  • (Integer)

    The length of the longest flag slop knows of



56
57
58
# File 'lib/slop.rb', line 56

def longest_flag
  @longest_flag
end

#optionsOptions (readonly)

Returns:



45
46
47
# File 'lib/slop.rb', line 45

def options
  @options
end

Class Method Details

.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
-------
program.rb --verbose -n 'Emily' -a 25

Parameters:

  • items (Array) (defaults to: ARGV)

    Items to parse into options.

Returns:

  • (Slop)

    Returns an instance of Slop.



33
34
35
# File 'lib/slop.rb', line 33

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.



40
41
42
# File 'lib/slop.rb', line 40

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

Instance Method Details

#[](key) ⇒ Object

Return the value of an option via the subscript operator.

Examples:

opts[:name] #=> "Emily"

Parameters:

  • key (Symbol)

    Option symbol.

Returns:

  • (Object)

    Returns the value associated with that option.



136
137
138
139
# File 'lib/slop.rb', line 136

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+

Since:

  • 1.5.0



189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/slop.rb', line 189

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

  options = @sloptions.merge(options)
  slop = Slop.new(options)
  @commands[label] = slop

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

  slop
end

#each(&block) ⇒ Object

Enumerable interface



126
127
128
# File 'lib/slop.rb', line 126

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

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

Add an object to be called when Slop has no values to parse

Examples:

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

Parameters:

  • proc (Object, nil)

    The object (which can be anything responding to :call)

Since:

  • 1.5.0



214
215
216
# File 'lib/slop.rb', line 214

def on_empty(obj=nil, &block)
  @on_empty ||= (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 a required option or not.

  • :options (Hash)

    Optional option configurations.

Returns:



161
162
163
164
165
166
167
168
169
170
# File 'lib/slop.rb', line 161

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

  short, long, desc, arg = clean_options(args)
  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 (defaults to: ARGV)


114
115
116
# File 'lib/slop.rb', line 114

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 (defaults to: ARGV)


121
122
123
# File 'lib/slop.rb', line 121

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

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

Returns the parsed list into a option/value hash.

Examples:

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

# symbols!
opts.to_hash(true) #=> { :name => 'Emily' }

Returns:

  • (Hash)


227
228
229
# File 'lib/slop.rb', line 227

def to_hash(symbols=false)
  @options.to_hash(symbols)
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:

  • (String)

    Help text.



253
254
255
256
# File 'lib/slop.rb', line 253

def to_s
  banner = "#{@banner}\n" if @banner
  (banner || '') + options.to_help
end