Class: Pry::CommandSet

Inherits:
Object show all
Includes:
Enumerable, Helpers::BaseHelpers
Defined in:
lib/pry/command_set.rb

Overview

This class is used to create sets of commands. Commands can be imported from different sets, aliased, removed, etc.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Helpers::BaseHelpers

#colorize_code, #command_dependencies_met?, #heading, #highlight, #not_a_real_file?, #safe_send, #silence_warnings, #stagger_output, #use_ansi_codes?

Methods included from Platform

#jruby?, #jruby_19?, #known_engines, #linux?, #mac_osx?, #mri?, #mri_19?, #mri_2?, #rbx?, #windows?, #windows_ansi?

Constructor Details

#initialize(*imported_sets) { ... } ⇒ CommandSet

Returns a new instance of CommandSet

Parameters:

  • imported_sets (Array<Commandset>)

    Sets which will be imported automatically

Yields:

  • Optional block run to define commands



18
19
20
21
22
23
# File 'lib/pry/command_set.rb', line 18

def initialize(*imported_sets, &block)
  @commands      = {}
  @helper_module = Module.new
  import(*imported_sets)
  instance_eval(&block) if block
end

Instance Attribute Details

#helper_moduleObject (readonly)

Returns the value of attribute helper_module



13
14
15
# File 'lib/pry/command_set.rb', line 13

def helper_module
  @helper_module
end

Instance Method Details

#[](pattern) ⇒ Pry::Command? Also known as: find_command

Find a command that matches the given line

Parameters:

  • pattern (String)

    The line that might be a command invocation

Returns:



324
325
326
327
328
329
330
# File 'lib/pry/command_set.rb', line 324

def [](pattern)
  @commands.values.select do |command|
    command.matches?(pattern)
  end.sort_by do |command|
    command.match_score(pattern)
  end.last
end

#[]=(pattern, command) ⇒ Pry::Command

Re-assign the command found at pattern with command.

Examples:

Pry.config.commands["help"] = MyHelpCommand

Parameters:

  • pattern (Regexp, String)

    The command to add or replace(found at pattern).

  • command (Pry::Command)

    The command to add.

Returns:

  • (Pry::Command)

    Returns the new command (matched with "pattern".)



348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
# File 'lib/pry/command_set.rb', line 348

def []=(pattern, command)
  if command.equal?(nil)
    return @commands.delete(pattern)
  end
  unless Class === command && command < Pry::Command
    raise TypeError, "command is not a subclass of Pry::Command"
  end
  bind_command_to_pattern = pattern != command.match
  if bind_command_to_pattern
    command_copy = command.dup
    command_copy.match = pattern
    @commands[pattern] = command_copy
  else
    @commands[pattern] = command
  end
end

#add_command(command) ⇒ Object

Add a command to set.

Parameters:

  • command (Command)

    a subclass of Pry::Command.



371
372
373
# File 'lib/pry/command_set.rb', line 371

def add_command(command)
  self[command.match] = command
end

#after_command(search) { ... } ⇒ Object

Deprecated.

Use Hooks#add_hook instead.

Execute a block of code after a command is invoked. The block also gets access to parameters that will be passed to the command and is evaluated in the same context.

Examples:

Display text 'command complete' after invoking command

Pry.config.commands.after_command("whereami") do |n|
  output.puts "command complete!"
end

Parameters:

  • search (String, Regexp)

    The match or listing of the command.

Yields:

  • The block to be run after the command.



144
145
146
147
# File 'lib/pry/command_set.rb', line 144

def after_command(search, &block)
  cmd = find_command_by_match_or_listing(search)
  cmd.hooks.add_hook("after_#{cmd.command_name}", random_hook_name, block)
end

#alias_command(match, action, options = {}) ⇒ Object

Aliases a command

Examples:

Creating an alias for ls -M

Pry.config.commands.alias_command "lM", "ls -M"

Pass explicit description (overriding default).

Pry.config.commands.alias_command "lM", "ls -M", :desc => "cutiepie"

Parameters:

  • match (String, Regex)

    The match of the alias (can be a regex).

  • action (String)

    The action to be performed (typically another command).

  • options (Hash) (defaults to: {})

    The optional configuration parameters, accepts the same as the command method, but also allows the command description to be passed this way too as :desc



212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/pry/command_set.rb', line 212

def alias_command(match, action,  options={})
  cmd = find_command(action) or fail "Command: `#{action}` not found"
  original_options = cmd.options.dup

  options = original_options.merge!({
                                      :desc => "Alias for `#{action}`",
                                      :listing => match
                                    }).merge!(options)

  # ensure default description is used if desc is nil
  desc = options.delete(:desc).to_s

  c = block_command match, desc, options do |*args|
    run action, *args
  end

  c.class_eval do
    define_method(:complete) do |input|
      cmd.new(context).complete(input)
    end
  end

  c.group "Aliases"

  c
end

#before_command(search) { ... } ⇒ Object

Deprecated.

Use Hooks#add_hook instead.

Execute a block of code before a command is invoked. The block also gets access to parameters that will be passed to the command and is evaluated in the same context.

Examples:

Display parameter before invoking command

Pry.config.commands.before_command("whereami") do |n|
  output.puts "parameter passed was #{n}"
end

Parameters:

  • search (String, Regexp)

    The match or listing of the command.

Yields:

  • The block to be run before the command.



129
130
131
132
# File 'lib/pry/command_set.rb', line 129

def before_command(search, &block)
  cmd = find_command_by_match_or_listing(search)
  cmd.hooks.add_hook("before_#{cmd.command_name}", random_hook_name, block)
end

#block_command(match, description = "No description.", options = {}) { ... } ⇒ Object Also known as: command

Defines a new Pry command.

Examples:

MyCommands = Pry::CommandSet.new do
  command "greet", "Greet somebody" do |name|
    puts "Good afternoon #{name.capitalize}!"
  end
end

# From pry:
# pry(main)> _pry_.commands = MyCommands
# pry(main)> greet john
# Good afternoon John!
# pry(main)> help greet
# Greet somebody

Regexp command

MyCommands = Pry::CommandSet.new do
  command /number-(\d+)/, "number-N regex command", :listing => "number" do |num, name|
    puts "hello #{name}, nice number: #{num}"
  end
end

# From pry:
# pry(main)> _pry_.commands = MyCommands
# pry(main)> number-10 john
# hello john, nice number: 10
# pry(main)> help number
# number-N regex command

Parameters:

  • match (String, Regexp)

    The start of invocations of this command.

  • description (String) (defaults to: "No description.")

    A description of the command.

  • options (Hash) (defaults to: {})

    The optional configuration parameters.

Options Hash (options):

  • :keep_retval (Boolean)

    Whether or not to use return value of the block for return of command or just to return nil (the default).

  • :requires_gem (Array<String>)

    Whether the command has any gem dependencies, if it does and dependencies not met then command is disabled and a stub proc giving instructions to install command is provided.

  • :interpolate (Boolean)

    Whether string #{} based interpolation is applied to the command arguments before executing the command. Defaults to true.

  • :listing (String)

    The listing name of the command. That is the name by which the command is looked up by help and by show-command. Necessary for commands with regex matches.

  • :use_prefix (Boolean)

    Whether the command uses Pry.config.command_prefix prefix (if one is defined). Defaults to true.

  • :shellwords (Boolean)

    Whether the command's arguments should be split using Shellwords instead of just split on spaces. Defaults to true.

Yields:

  • The action to perform. The parameters in the block determines the parameters the command will receive. All parameters passed into the block will be strings. Successive command parameters are separated by whitespace at the Pry prompt.



78
79
80
81
82
83
# File 'lib/pry/command_set.rb', line 78

def block_command(match, description="No description.", options={}, &block)
  description, options = ["No description.", description] if description.is_a?(Hash)
  options = Pry::Command.default_options(match).merge!(options)

  @commands[match] = Pry::BlockCommand.subclass(match, description, options, helper_module, &block)
end

#complete(search, context = {}) ⇒ Array<String>

Generate completions for the user's search.

Parameters:

  • search (String)

    The line to search for

  • context (Hash) (defaults to: {})

    The context to create the command with

Returns:

  • (Array<String>)


417
418
419
420
421
422
423
424
425
# File 'lib/pry/command_set.rb', line 417

def complete(search, context={})
  if command = find_command(search)
    command.new(context).complete(search)
  else
    @commands.keys.select do |key|
      String === key && key.start_with?(search)
    end.map{ |key| key + " " }
  end
end

#create_command(match, description = "No description.", options = {}) { ... } ⇒ Object

Defines a new Pry command class.

Examples:

Pry::Commands.create_command "echo", "echo's the input", :shellwords => false do
  def options(opt)
    opt.banner "Usage: echo [-u | -d] <string to echo>"
    opt.on :u, :upcase, "ensure the output is all upper-case"
    opt.on :d, :downcase, "ensure the output is all lower-case"
  end

  def process
    raise Pry::CommandError, "-u and -d makes no sense" if opts.present?(:u) && opts.present?(:d)
    result = args.join(" ")
    result.downcase! if opts.present?(:downcase)
    result.upcase! if opts.present?(:upcase)
    output.puts result
  end
end

Parameters:

  • match (String, Regexp)

    The start of invocations of this command.

  • description (String) (defaults to: "No description.")

    A description of the command.

  • options (Hash) (defaults to: {})

    The optional configuration parameters, see #command

Yields:

  • The class body's definition.



110
111
112
113
114
115
116
117
# File 'lib/pry/command_set.rb', line 110

def create_command(match, description="No description.", options={}, &block)
  description, options = ["No description.", description] if description.is_a?(Hash)
  options = Pry::Command.default_options(match).merge!(options)

  @commands[match] = Pry::ClassCommand.subclass(match, description, options, helper_module, &block)
  @commands[match].class_eval(&block)
  @commands[match]
end

#delete(*searches) ⇒ Object

Removes some commands from the set

Parameters:

  • searches (Array<String>)

    the matches or listings of the commands to remove



160
161
162
163
164
165
# File 'lib/pry/command_set.rb', line 160

def delete(*searches)
  searches.each do |search|
    cmd = find_command_by_match_or_listing(search)
    @commands.delete cmd.match
  end
end

#desc(search, description = nil) ⇒ Object

Sets or gets the description for a command (replacing the old description). Returns current description if no description parameter provided.

Examples:

Setting

MyCommands = Pry::CommandSet.new do
  desc "help", "help description"
end

Getting

Pry.config.commands.desc "amend-line"

Parameters:

  • search (String, Regexp)

    The command match.

  • description (String?) (defaults to: nil)

    (nil) The command description.



285
286
287
288
289
290
# File 'lib/pry/command_set.rb', line 285

def desc(search, description=nil)
  cmd = find_command_by_match_or_listing(search)
  return cmd.description if !description

  cmd.description = description
end

#disabled_command(name_of_disabled_command, message, matcher = name_of_disabled_command) ⇒ Object



263
264
265
266
267
268
269
270
271
272
# File 'lib/pry/command_set.rb', line 263

def disabled_command(name_of_disabled_command, message, matcher=name_of_disabled_command)
  create_command name_of_disabled_command do
    match matcher
    description ""

    define_method(:process) do
      output.puts "DISABLED: #{message}"
    end
  end
end

#each(&block) ⇒ Object



154
155
156
# File 'lib/pry/command_set.rb', line 154

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

#find_command_by_match_or_listing(match_or_listing) ⇒ Command

Returns The command object matched.

Parameters:

  • match_or_listing (String, Regexp)

    The match or listing of a command. of the command to retrieve.

Returns:

  • (Command)

    The command object matched.



195
196
197
198
199
# File 'lib/pry/command_set.rb', line 195

def find_command_by_match_or_listing(match_or_listing)
  cmd = (@commands[match_or_listing] ||
    Pry::Helpers::BaseHelpers.find_command(match_or_listing, @commands))
  cmd or raise ArgumentError, "Cannot find a command: '#{match_or_listing}'!"
end

#find_command_for_help(search) ⇒ Pry::Command?

Find the command that the user might be trying to refer to.

Parameters:

  • search (String)

    The user's search.

Returns:



378
379
380
381
382
383
384
# File 'lib/pry/command_set.rb', line 378

def find_command_for_help(search)
  find_command(search) || (begin
    find_command_by_match_or_listing(search)
  rescue ArgumentError
    nil
  end)
end

#helpers { ... } ⇒ Object

Defines helpers methods for this command sets. Those helpers are only defined in this command set.

Examples:

helpers do
  def hello
    puts "Hello!"
  end

  include OtherModule
end

Yields:

  • A block defining helper methods



304
305
306
# File 'lib/pry/command_set.rb', line 304

def helpers(&block)
  helper_module.class_eval(&block)
end

#import(*sets) ⇒ Pry::CommandSet

Imports all the commands from one or more sets.

Parameters:

  • sets (Array<CommandSet>)

    Command sets, all of the commands of which will be imported.

Returns:



171
172
173
174
175
176
177
# File 'lib/pry/command_set.rb', line 171

def import(*sets)
  sets.each do |set|
    @commands.merge! set.to_hash
    helper_module.send :include, set.helper_module
  end
  self
end

#import_from(set, *matches) ⇒ Pry::CommandSet

Imports some commands from a set

Parameters:

  • set (CommandSet)

    Set to import commands from

  • matches (Array<String>)

    Commands to import

Returns:



183
184
185
186
187
188
189
190
# File 'lib/pry/command_set.rb', line 183

def import_from(set, *matches)
  helper_module.send :include, set.helper_module
  matches.each do |match|
    cmd = set.find_command_by_match_or_listing(match)
    @commands[cmd.match] = cmd
  end
  self
end

#list_commandsArray Also known as: keys

Returns The list of commands provided by the command set.

Returns:

  • (Array)

    The list of commands provided by the command set.



311
312
313
# File 'lib/pry/command_set.rb', line 311

def list_commands
  @commands.keys
end

#process_line(val, context = {}) ⇒ CommandSet::Result

Process the given line to see whether it needs executing as a command.

Parameters:

  • val (String)

    The line to execute

  • context (Hash) (defaults to: {})

    The context to execute the commands with

Returns:

  • (CommandSet::Result)


397
398
399
400
401
402
403
404
405
# File 'lib/pry/command_set.rb', line 397

def process_line(val, context={})
  if command = find_command(val)
    context = context.merge(:command_set => self)
    retval = command.new(context).process_line(val)
    Result.new(true, retval)
  else
    Result.new(false)
  end
end

#random_hook_nameObject (private)



149
150
151
# File 'lib/pry/command_set.rb', line 149

def random_hook_name
  (0...8).map { ('a'..'z').to_a[rand(26)] }.join
end

#rename_command(new_match, search, options = {}) ⇒ Object

Rename a command. Accepts either match or listing for the search.

Examples:

Renaming the ls command and changing its description.

Pry.config.commands.rename "dir", "ls", :description => "DOS friendly ls"

Parameters:

  • new_match (String, Regexp)

    The new match for the command.

  • search (String, Regexp)

    The command's current match or listing.

  • options (Hash) (defaults to: {})

    The optional configuration parameters, accepts the same as the command method, but also allows the command description to be passed this way too.



248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/pry/command_set.rb', line 248

def rename_command(new_match, search, options={})
  cmd = find_command_by_match_or_listing(search)

  options = {
    :listing     => new_match,
    :description => cmd.description
  }.merge!(options)

  @commands[new_match] = cmd.dup
  @commands[new_match].match = new_match
  @commands[new_match].description = options.delete(:description)
  @commands[new_match].options.merge!(options)
  @commands.delete(cmd.match)
end

#run_command(context, match, *args) ⇒ Object



408
409
410
411
# File 'lib/pry/command_set.rb', line 408

def run_command(context, match, *args)
  command = @commands[match] or raise NoCommandError.new(match, self)
  command.new(context).call_safely(*args)
end

#to_hashObject Also known as: to_h



316
317
318
# File 'lib/pry/command_set.rb', line 316

def to_hash
  @commands.dup
end

#valid_command?(val) ⇒ Boolean

Is the given line a command invocation?

Parameters:

  • val (String)

Returns:

  • (Boolean)


389
390
391
# File 'lib/pry/command_set.rb', line 389

def valid_command?(val)
  !!find_command(val)
end