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.8.0'

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:

  • opts (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


94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/slop.rb', line 94

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[:multiple_switches]
  @autocreate = sloptions[:autocreate]
  @arguments = sloptions[:arguments]
  @on_empty = sloptions[:on_empty]
  @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
      (sloptions[:io] || $stderr).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:



311
312
313
314
# File 'lib/slop.rb', line 311

def method_missing(meth, *args, &block)
  super unless meth.to_s[-1, 1] == '?'
  present? 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)

    The current banner



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

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

#commandsHash (readonly)

Returns:

  • (Hash)


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

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



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

def longest_flag
  @longest_flag
end

#optionsOptions (readonly)

Returns:



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

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

Parameters:

  • items (Array) (defaults to: ARGV)

    Items to parse into options.

Returns:

  • (Slop)

    Returns an instance of Slop



31
32
33
# File 'lib/slop.rb', line 31

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



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

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



166
167
168
169
# File 'lib/slop.rb', line 166

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



221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/slop.rb', line 221

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

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

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

  slop
end

#each(&block) ⇒ Object

Enumerable interface



156
157
158
# File 'lib/slop.rb', line 156

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

#execute(obj = nil, &block) ⇒ 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:

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

    The object to be triggered when this command is invoked

Since:

  • 1.8.0



280
281
282
283
284
285
286
# File 'lib/slop.rb', line 280

def execute(obj=nil, &block)
  if obj || block_given?
    @execution_block = obj || block
  elsif @execution_block.respond_to?(:call)
    @execution_block.call(self)
  end
end

#inspectObject



343
344
345
346
# File 'lib/slop.rb', line 343

def inspect
  "#<Slop config_options=#{@sloptions.inspect}\n  " +
  options.map(&:inspect).join("\n  ") + "\n>"
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



245
246
247
# File 'lib/slop.rb', line 245

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



259
260
261
# File 'lib/slop.rb', line 259

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:



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

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

  short, long, desc, arg, extras = clean_options args
  options.merge!(extras)
  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



144
145
146
# File 'lib/slop.rb', line 144

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



151
152
153
# File 'lib/slop.rb', line 151

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

#present?(option_name) ⇒ 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 to check

Returns:

  • (Boolean)

    true if this option is present, false otherwise

Since:

  • 1.5.0



324
325
326
# File 'lib/slop.rb', line 324

def present?(option_name)
  !!get(option_name)
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)


296
297
298
# File 'lib/slop.rb', line 296

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.



337
338
339
340
# File 'lib/slop.rb', line 337

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