Class: Pry

Inherits:
Object show all
Extended by:
Forwardable
Defined in:
lib/pry/pry_instance.rb,
lib/pry.rb,
lib/pry/cli.rb,
lib/pry/code.rb,
lib/pry/hooks.rb,
lib/pry/config.rb,
lib/pry/indent.rb,
lib/pry/method.rb,
lib/pry/command.rb,
lib/pry/history.rb,
lib/pry/plugins.rb,
lib/pry/version.rb,
lib/pry/commands.rb,
lib/pry/rbx_path.rb,
lib/pry/pry_class.rb,
lib/pry/completion.rb,
lib/pry/rbx_method.rb,
lib/pry/command_set.rb,
lib/pry/helpers/text.rb,
lib/pry/history_array.rb,
lib/pry/wrapped_module.rb,
lib/pry/module_candidate.rb,
lib/pry/repl_file_loader.rb,
lib/pry/custom_completions.rb,
lib/pry/default_commands/cd.rb,
lib/pry/default_commands/ls.rb,
lib/pry/helpers/base_helpers.rb,
lib/pry/default_commands/gems.rb,
lib/pry/default_commands/gist.rb,
lib/pry/default_commands/help.rb,
lib/pry/default_commands/hist.rb,
lib/pry/default_commands/misc.rb,
lib/pry/helpers/command_helpers.rb,
lib/pry/helpers/options_helpers.rb,
lib/pry/default_commands/context.rb,
lib/pry/default_commands/editing.rb,
lib/pry/default_commands/commands.rb,
lib/pry/default_commands/whereami.rb,
lib/pry/default_commands/easter_eggs.rb,
lib/pry/default_commands/find_method.rb,
lib/pry/helpers/documentation_helpers.rb,
lib/pry/default_commands/introspection.rb,
lib/pry/extended_commands/experimental.rb,
lib/pry/default_commands/navigating_pry.rb,
lib/pry/default_commands/input_and_output.rb

Overview

Pry is a powerful alternative to the standard IRB shell for Ruby. It features syntax highlighting, a flexible plugin architecture, runtime invocation and source and documentation browsing.

Pry can be started similar to other command line utilities by simply running the following command:

pry

Once inside Pry you can invoke the help message:

help

This will show a list of available commands and their usage. For more information about Pry you can refer to the following resources:

Defined Under Namespace

Modules: DefaultCommands, ExtendCommandBundle, ExtendedCommands, Helpers, InputCompleter, RbxMethod, RbxPath, RescuableException Classes: BlockCommand, CLI, ClassCommand, Code, Command, CommandError, CommandSet, Config, History, HistoryArray, Hooks, Indent, Method, NoCommandError, NonMethodContextError, ObsoleteError, PluginManager, REPLFileLoader, Result, WrappedModule

Constant Summary collapse

DEFAULT_HOOKS =

The default hooks - display messages when beginning and ending Pry sessions.

Pry::Hooks.new.add_hook(:before_session, :default) do |out, target, _pry_|
  next if _pry_.quiet?
  _pry_.run_command("whereami --quiet", "", target)
end
DEFAULT_PRINT =

The default print

proc do |output, value|
  stringified = begin
                  value.pretty_inspect
                rescue RescuableException
                  nil
                end

  unless String === stringified
    # Read the class name off of the singleton class to provide a default inspect.
    klass = (class << value; self; end).ancestors.first
    stringified = "#<#{klass}:0x#{value.__id__.to_s(16)}>"
  end

  nonce = rand(0x100000000).to_s(16) # whatever

  colorized = Helpers::BaseHelpers.colorize_code(stringified.gsub(/#</, "%<#{nonce}"))

  # avoid colour-leak from CodeRay and any of the users' previous output
  colorized = colorized.sub(/(\n*)$/, "\e[0m\\1") if Pry.color

  Helpers::BaseHelpers.stagger_output("=> #{colorized.gsub(/%<(.*?)#{nonce}/, '#<\1')}", output)
end
SIMPLE_PRINT =

may be convenient when working with enormous objects and pretty_print is too slow

proc do |output, value|
  begin
    output.puts "=> #{value.inspect}"
  rescue RescuableException
    output.puts "=> unknown"
  end
end
CLIPPED_PRINT =

useful when playing with truly enormous objects

proc do |output, value|
  output.puts "=> #{Pry.view_clip(value)}"
end
DEFAULT_EXCEPTION_HANDLER =

Will only show the first line of the backtrace

proc do |output, exception, _|
  output.puts "#{exception.class}: #{exception.message}"
  output.puts "from #{exception.backtrace.first}"
end
DEFAULT_EXCEPTION_WHITELIST =

Don't catch these exceptions

[SystemExit, SignalException]
DEFAULT_PROMPT =

The default prompt; includes the target and nesting level

[
 proc { |target_self, nest_level, pry|
   "[#{pry.input_array.size}] pry(#{Pry.view_clip(target_self)})#{":#{nest_level}" unless nest_level.zero?}> "
 },

 proc { |target_self, nest_level, pry|
   "[#{pry.input_array.size}] pry(#{Pry.view_clip(target_self)})#{":#{nest_level}" unless nest_level.zero?}* "
 }
]
SIMPLE_PROMPT =

A simple prompt - doesn't display target or nesting level

[proc { ">> " }, proc { " | " }]
SHELL_PROMPT =
[
 proc { |target_self, _, _| "pry #{Pry.view_clip(target_self)}:#{Dir.pwd} $ " },
 proc { |target_self, _, _| "pry #{Pry.view_clip(target_self)}:#{Dir.pwd} * " }
]
[
 proc do |conf|
   tree = conf.binding_stack.map { |b| Pry.view_clip(b.eval("self")) }.join " / "
   "[#{conf.expr_number}] (pry) #{tree}: #{conf.nesting_level}> "
 end,
 proc do |conf|
   tree = conf.binding_stack.map { |b| Pry.view_clip(b.eval("self")) }.join " / "
   "[#{conf.expr_number}] (pry) #{tree}: #{conf.nesting_level}* "
 end,
]
DEFAULT_CONTROL_D_HANDLER =

Deal with the ^D key being pressed, different behaviour in different cases: 1) In an expression - behave like ! command (clear input buffer) 2) At top-level session - behave like exit command (break out of repl loop) 3) In a nested session - behave likecd ..` (pop a binding)

proc do |eval_string, _pry_|
  if !eval_string.empty?
    # Clear input buffer.
    eval_string.replace("")
  elsif _pry_.binding_stack.one?
    # ^D at top-level breaks out of a REPL loop.
    _pry_.binding_stack.clear
    throw(:breakout)
  else
    # Otherwise, saves current binding stack as old stack and pops last
    # binding out of binding stack (the old stack still has that binding).
    _pry_.command_state["cd"].old_stack = _pry_.binding_stack.dup
    _pry_.binding_stack.pop
  end
end
DEFAULT_SYSTEM =
proc do |output, cmd, _|
  if !system(cmd)
    output.puts "Error: there was a problem executing system command: #{cmd}"
  end
end
VERSION =
"0.9.10"
Commands =

Default commands used by Pry.

Pry::CommandSet.new do
  import DefaultCommands::Misc
  import DefaultCommands::Help
  import DefaultCommands::Gems
  import DefaultCommands::Context
  import DefaultCommands::NavigatingPry
  import DefaultCommands::Editing
  import DefaultCommands::InputAndOutput
  import DefaultCommands::Introspection
  import DefaultCommands::EasterEggs
  import DefaultCommands::Commands
end
RC_FILES =

The RC Files to load.

["~/.pryrc"]
LOCAL_RC_FILE =
"./.pryrc"
DEFAULT_CUSTOM_COMPLETIONS =

This proc will be instance_eval's against the active Pry instance

proc { commands.commands.keys }
FILE_COMPLETIONS =
proc { commands.commands.keys + Dir.entries('.') }

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Pry

Create a new Pry object.

Parameters:

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

    The optional configuration parameters.

Options Hash (options):

  • :input (#readline)

    The object to use for input.

  • :output (#puts)

    The object to use for output.

  • :commands (Pry::CommandBase)

    The object to use for commands.

  • :hooks (Hash)

    The defined hook Procs

  • :prompt (Array<Proc>)

    The array of Procs to use for the prompts.

  • :print (Proc)

    The Proc to use for the 'print'

  • :quiet (Boolean)

    If true, omit the whereami banner when starting. component of the REPL. (see print.rb)



83
84
85
86
87
88
89
# File 'lib/pry/pry_instance.rb', line 83

def initialize(options={})
  refresh(options)

  @binding_stack = []
  @indent        = Pry::Indent.new
  @command_state = {}
end

Class Attribute Details

.cliBoolean

Returns Whether Pry was activated from the command line.

Returns:

  • (Boolean)

    Whether Pry was activated from the command line.



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

def cli
  @cli
end

.configOpenStruct

Return Pry's config object.

Returns:

  • (OpenStruct)

    Return Pry's config object.



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

def config
  @config
end

.current_lineFixnum

Returns The current input line.

Returns:

  • (Fixnum)

    The current input line.



29
30
31
# File 'lib/pry/pry_class.rb', line 29

def current_line
  @current_line
end

.custom_completionsProc

Get/Set the Proc that defines extra Readline completions (on top of the ones defined for IRB).

Examples:

Add file names to completion list

Pry.custom_completions = proc { Dir.entries('.') }

Returns:

  • (Proc)

    The Proc that defines extra Readline completions (on top



26
27
28
# File 'lib/pry/pry_class.rb', line 26

def custom_completions
  @custom_completions
end

.eval_pathString

Returns The FILE for the eval(). Should be "(pry)" by default.

Returns:

  • (String)

    The FILE for the eval(). Should be "(pry)" by default.



36
37
38
# File 'lib/pry/pry_class.rb', line 36

def eval_path
  @eval_path
end

.historyHistory

Return Pry's line history object.

Returns:

  • (History)

    Return Pry's line history object.



42
43
44
# File 'lib/pry/pry_class.rb', line 42

def history
  @history
end

.line_bufferArray

Returns The Array of evaluated expressions.

Returns:

  • (Array)

    The Array of evaluated expressions.



32
33
34
# File 'lib/pry/pry_class.rb', line 32

def line_buffer
  @line_buffer
end

.quietBoolean

Returns Whether Pry sessions are quiet by default.

Returns:

  • (Boolean)

    Whether Pry sessions are quiet by default.



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

def quiet
  @quiet
end

.toplevel_bindingBinding

Returns A top level binding with no local variables.

Returns:

  • (Binding)

    A top level binding with no local variables



51
52
53
# File 'lib/pry/pry_class.rb', line 51

def toplevel_binding
  @toplevel_binding
end

Instance Attribute Details

#backtraceObject

Returns the value of attribute backtrace.



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

def backtrace
  @backtrace
end

#binding_stackObject

Returns the value of attribute binding_stack.



37
38
39
# File 'lib/pry/pry_instance.rb', line 37

def binding_stack
  @binding_stack
end

#command_stateObject (readonly)

This is exposed via Pry::Command#state.



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

def command_state
  @command_state
end

#commandsObject

Returns the value of attribute commands.



28
29
30
# File 'lib/pry/pry_instance.rb', line 28

def commands
  @commands
end

#custom_completionsObject

Returns the value of attribute custom_completions.



35
36
37
# File 'lib/pry/pry_instance.rb', line 35

def custom_completions
  @custom_completions
end

#exception_handlerObject

Returns the value of attribute exception_handler.



30
31
32
# File 'lib/pry/pry_instance.rb', line 30

def exception_handler
  @exception_handler
end

#extra_sticky_localsObject

Returns the value of attribute extra_sticky_locals.



50
51
52
# File 'lib/pry/pry_instance.rb', line 50

def extra_sticky_locals
  @extra_sticky_locals
end

#hooksObject

Special treatment for hooks as we want to alert people of the changed API



59
60
61
# File 'lib/pry/pry_instance.rb', line 59

def hooks
  @hooks
end

#inputObject

Returns the value of attribute input.



26
27
28
# File 'lib/pry/pry_instance.rb', line 26

def input
  @input
end

#input_arrayObject (readonly)

Returns the value of attribute input_array.



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

def input_array
  @input_array
end

#input_stackObject

Returns the value of attribute input_stack.



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

def input_stack
  @input_stack
end

#last_dirObject

Returns the value of attribute last_dir.



41
42
43
# File 'lib/pry/pry_instance.rb', line 41

def last_dir
  @last_dir
end

#last_exceptionObject

Returns the value of attribute last_exception.



43
44
45
# File 'lib/pry/pry_instance.rb', line 43

def last_exception
  @last_exception
end

#last_fileObject

Returns the value of attribute last_file.



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

def last_file
  @last_file
end

#last_resultObject

Returns the value of attribute last_result.



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

def last_result
  @last_result
end

#outputObject

Returns the value of attribute output.



27
28
29
# File 'lib/pry/pry_instance.rb', line 27

def output
  @output
end

#output_arrayObject (readonly)

Returns the value of attribute output_array.



46
47
48
# File 'lib/pry/pry_instance.rb', line 46

def output_array
  @output_array
end

Returns the value of attribute print.



29
30
31
# File 'lib/pry/pry_instance.rb', line 29

def print
  @print
end

#quietObject Also known as: quiet?

Returns the value of attribute quiet.



32
33
34
# File 'lib/pry/pry_instance.rb', line 32

def quiet
  @quiet
end

#suppress_outputObject

Returns the value of attribute suppress_output.



52
53
54
# File 'lib/pry/pry_instance.rb', line 52

def suppress_output
  @suppress_output
end

Class Method Details

.binding_for(target) ⇒ Binding

Return a Binding object for target or return target if it is already a Binding. In the case where target is top-level then return TOPLEVEL_BINDING

Parameters:

  • target (Object)

    The object to get a Binding object for.

Returns:

  • (Binding)

    The Binding object.



375
376
377
378
379
380
381
382
383
384
385
# File 'lib/pry/pry_class.rb', line 375

def self.binding_for(target)
  if Binding === target
    target
  else
    if TOPLEVEL_BINDING.eval('self') == target
      TOPLEVEL_BINDING
    else
      target.__binding__
    end
  end
end

.Code(obj) ⇒ Object

Convert the given object into an instance of Pry::Code, if it isn't already one.

Parameters:



8
9
10
11
12
13
14
15
16
17
# File 'lib/pry/code.rb', line 8

def Code(obj)
  case obj
  when Code
    obj
  when ::Method, UnboundMethod, Proc, Pry::Method
    Code.from_method(obj)
  else
    Code.new(obj)
  end
end

.default_editor_for_platformObject



230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/pry/pry_class.rb', line 230

def self.default_editor_for_platform
  return ENV['VISUAL'] if ENV['VISUAL'] and not ENV['VISUAL'].empty?
  return ENV['EDITOR'] if ENV['EDITOR'] and not ENV['EDITOR'].empty?

  if Helpers::BaseHelpers.windows?
    'notepad'
  else
    %w(editor nano vi).detect do |editor|
      system("which #{editor} > /dev/null 2>&1")
    end
  end
end

.delegate_accessors(delagatee, *names) ⇒ Object

convenience method



16
17
18
19
# File 'lib/pry/pry_class.rb', line 16

def self.delegate_accessors(delagatee, *names)
  def_delegators delagatee, *names
  def_delegators delagatee, *names.map { |v| "#{v}=" }
end

.fix_coderay_colorsObject

To avoid mass-confusion, we change the default colour of "white" to "blue" enabling global legibility



344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
# File 'lib/pry/pry_class.rb', line 344

def self.fix_coderay_colors
    to_fix = if (CodeRay::Encoders::Terminal::TOKEN_COLORS rescue nil)
               # CodeRay 1.0.0
               CodeRay::Encoders::Terminal::TOKEN_COLORS
             else
               # CodeRay 0.9
               begin
                 require 'coderay/encoders/term'
                 CodeRay::Encoders::Term::TOKEN_COLORS
               rescue
               end
             end

    to_fix[:comment] = "0;34" if to_fix
end

.initObject

Basic initialization.



361
362
363
364
365
366
367
368
# File 'lib/pry/pry_class.rb', line 361

def self.init
  @plugin_manager ||= PluginManager.new
  self.config ||= Config.new
  self.history ||= History.new

  reset_defaults
  locate_plugins
end

.initial_session?Boolean

Returns Whether this is the first time a Pry session has been started since loading the Pry class.

Returns:

  • (Boolean)

    Whether this is the first time a Pry session has been started since loading the Pry class.



197
198
199
# File 'lib/pry/pry_class.rb', line 197

def self.initial_session?
  @initial_session
end

.initial_session_setupObject

Do basic setup for initial session. Including: loading .pryrc, loading plugins, loading requires, and loading history.



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/pry/pry_class.rb', line 101

def self.initial_session_setup

  return if !initial_session?

  # note these have to be loaded here rather than in pry_instance as
  # we only want them loaded once per entire Pry lifetime.
  load_rc if Pry.config.should_load_rc
  load_local_rc if Pry.config.should_load_local_rc
  load_plugins if Pry.config.should_load_plugins
  load_requires if Pry.config.should_load_requires
  load_history if Pry.config.history.should_load
  load_traps if Pry.config.should_trap_interrupts

  @initial_session = false
end

.load_file_at_toplevel(file_name) ⇒ Object

Load the given file in the context of Pry.toplevel_binding

Parameters:

  • file_name (String)

    The unexpanded file path.



63
64
65
66
67
68
69
70
# File 'lib/pry/pry_class.rb', line 63

def self.load_file_at_toplevel(file_name)
  full_name = File.expand_path(file_name)
  begin
    toplevel_binding.eval(File.read(full_name)) if File.exists?(full_name)
  rescue RescuableException => e
    puts "Error loading #{file_name}: #{e}"
  end
end

.load_file_through_repl(file_name) ⇒ Object

Execute the file through the REPL loop, non-interactively.

Parameters:

  • file_name (String)

    File name to load through the REPL.



159
160
161
162
# File 'lib/pry/pry_class.rb', line 159

def self.load_file_through_repl(file_name)
  require "pry/repl_file_loader"
  REPLFileLoader.new(file_name).load
end

.load_historyObject

Load Readline history if required.



186
187
188
# File 'lib/pry/pry_class.rb', line 186

def self.load_history
  Pry.history.load
end

.load_local_rcObject

Load the local RC file (./.pryrc)



81
82
83
# File 'lib/pry/pry_class.rb', line 81

def self.load_local_rc
  load_file_at_toplevel(LOCAL_RC_FILE)
end

.load_rcObject

Load the rc files given in the Pry::RC_FILES array. This method can also be used to reload the files if they have changed.



74
75
76
77
78
# File 'lib/pry/pry_class.rb', line 74

def self.load_rc
  RC_FILES.uniq.each do |file_name|
    load_file_at_toplevel(file_name)
  end
end

.load_requiresObject

Load any Ruby files specified with the -r flag on the command line.



86
87
88
89
90
# File 'lib/pry/pry_class.rb', line 86

def self.load_requires
  Pry.config.requires.each do |file|
    require file
  end
end

.load_trapsObject

Trap interrupts on jruby, and make them behave like MRI so we can catch them.



94
95
96
# File 'lib/pry/pry_class.rb', line 94

def self.load_traps
  trap('INT'){ raise Interrupt }
end

.Method(obj) ⇒ Object

If the given object is a Pry::Method, return it unaltered. If it's anything else, return it wrapped in a Pry::Method instance.



8
9
10
11
12
13
14
# File 'lib/pry/method.rb', line 8

def Method(obj)
  if obj.is_a? Pry::Method
    obj
  else
    Pry::Method.new(obj)
  end
end

.reset_defaultsObject

Set all the configurable options back to their default values



328
329
330
331
332
333
334
335
336
337
338
339
340
# File 'lib/pry/pry_class.rb', line 328

def self.reset_defaults
  set_config_defaults

  @initial_session = true

  self.custom_completions = DEFAULT_CUSTOM_COMPLETIONS
  self.cli = false
  self.current_line = 1
  self.line_buffer = [""]
  self.eval_path = "(pry)"

  fix_coderay_colors
end

.run_command(command_string, options = {}) ⇒ Object

Run a Pry command from outside a session. The commands available are those referenced by Pry.commands (the default command set).

Examples:

Run at top-level with no output.

Pry.run_command "ls"

Run under Pry class, returning only public methods.

Pry.run_command "ls -m", :context => Pry

Display command output.

Pry.run_command "ls -av", :show_output => true

Parameters:

  • command_string (String)

    The Pry command (including arguments, if any).

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

    Optional named parameters.

Options Hash (options):

  • :context (Object, Binding)

    The object context to run the command under. Defaults to TOPLEVEL_BINDING (main).

  • :show_output (Boolean)

    Whether to show command output. Defaults to true.

Returns:

  • (Object)

    The return value of the Pry command.



217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/pry/pry_class.rb', line 217

def self.run_command(command_string, options={})
  options = {
    :context => TOPLEVEL_BINDING,
    :show_output => true,
    :output => Pry.output,
    :commands => Pry.commands
  }.merge!(options)

  output = options[:show_output] ? options[:output] : StringIO.new

  Pry.new(:output => output, :input => StringIO.new(command_string), :commands => options[:commands], :prompt => proc {""}, :hooks => Pry::Hooks.new).rep(options[:context])
end

.save_historyObject

Save new lines of Readline history if required.



191
192
193
# File 'lib/pry/pry_class.rb', line 191

def self.save_history
  Pry.history.save
end

.set_config_defaultsObject



243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# File 'lib/pry/pry_class.rb', line 243

def self.set_config_defaults
  config.input = Readline
  config.output = $stdout
  config.commands = Pry::Commands
  config.prompt = DEFAULT_PROMPT
  config.print = DEFAULT_PRINT
  config.exception_handler = DEFAULT_EXCEPTION_HANDLER
  config.exception_whitelist = DEFAULT_EXCEPTION_WHITELIST
  config.default_window_size = 5
  config.hooks = DEFAULT_HOOKS
  config.input_stack = []
  config.color = Helpers::BaseHelpers.use_ansi_codes?
  config.pager = true
  config.system = DEFAULT_SYSTEM
  config.editor = default_editor_for_platform
  config.should_load_rc = true
  config.should_load_local_rc = true
  config.should_trap_interrupts = Helpers::BaseHelpers.jruby?
  config.disable_auto_reload = false
  config.command_prefix = ""
  config.auto_indent = Helpers::BaseHelpers.use_ansi_codes?
  config.correct_indent = true
  config.collision_warning = false

  config.gist ||= OpenStruct.new
  config.gist.inspecter = proc(&:pretty_inspect)

  config.should_load_plugins = true

  config.requires ||= []
  config.should_load_requires = true

  config.history ||= OpenStruct.new
  config.history.should_save = true
  config.history.should_load = true
  config.history.file = File.expand_path("~/.pry_history") rescue nil

  if config.history.file.nil?
    config.should_load_rc = false
    config.history.should_save = false
    config.history.should_load = false
  end

  config.control_d_handler = DEFAULT_CONTROL_D_HANDLER

  config.memory_size = 100

  config.extra_sticky_locals = {}

  config.ls ||= OpenStruct.new({
    :heading_color            => :default,

    :public_method_color      => :default,
    :private_method_color     => :green,
    :protected_method_color   => :yellow,
    :method_missing_color     => :bright_red,

    :local_var_color          => :default,
    :pry_var_color            => :red,         # e.g. _, _pry_, _file_

    :instance_var_color       => :blue,        # e.g. @foo
    :class_var_color          => :bright_blue, # e.g. @@foo

    :global_var_color         => :default,     # e.g. $CODERAY_DEBUG, $eventmachine_library
    :builtin_global_color     => :cyan,        # e.g. $stdin, $-w, $PID
    :pseudo_global_color      => :cyan,        # e.g. $~, $1..$9, $LAST_MATCH_INFO

    :constant_color           => :default,     # e.g. VERSION, ARGF
    :class_constant_color     => :blue,        # e.g. Object, Kernel
    :exception_constant_color => :magenta,     # e.g. Exception, RuntimeError
    :unloaded_constant_color  => :yellow,      # Any constant that is still in .autoload? state

    # What should separate items listed by ls? (TODO: we should allow a columnar layout)
    :separator                => "  ",

    # Any methods defined on these classes, or modules included into these classes, will not
    # be shown by ls unless the -v flag is used.
    # A user of Rails may wih to add ActiveRecord::Base to the list.
    # add the following to your .pryrc:
    # Pry.config.ls.ceiling << ActiveRecord::Base if defined? ActiveRecordBase
    :ceiling                  => [Object, Module, Class]
  })
end

.start(target = toplevel_binding, options = {}) ⇒ Object

Start a Pry REPL. This method also loads the files specified in Pry::RC_FILES the first time it is invoked.

Examples:

Pry.start(Object.new, :input => MyInput.new)

Parameters:

  • target (Object, Binding) (defaults to: toplevel_binding)

    The receiver of the Pry session

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

Options Hash (options):

  • :input (#readline)

    The object to use for input.

  • :output (#puts)

    The object to use for output.

  • :commands (Pry::CommandBase)

    The object to use for commands.

  • :hooks (Hash)

    The defined hook Procs

  • :prompt (Array<Proc>)

    The array of Procs to use for the prompts.

  • :print (Proc)

    The Proc to use for the 'print'

  • :quiet (Boolean)

    If true, omit the whereami banner when starting. component of the REPL. (see print.rb)



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/pry/pry_class.rb', line 125

def self.start(target=toplevel_binding, options={})
  target = Pry.binding_for(target)
  initial_session_setup

  # create the Pry instance to manage the session
  pry_instance = new(options)

  # save backtrace
  pry_instance.backtrace = caller

  # if Pry was started via binding.pry, elide that from the backtrace.
  pry_instance.backtrace.shift if pry_instance.backtrace.first =~ /pry.*core_extensions.*pry/

  # yield the binding_stack to the hook for modification
  pry_instance.exec_hook(:when_started, target, options, pry_instance)

  if !pry_instance.binding_stack.empty?
    head = pry_instance.binding_stack.pop
  else
    head = target
  end

  # Clear the line before starting Pry. This fixes the issue discussed here:
  # https://github.com/pry/pry/issues/566
  if Pry.config.auto_indent
    Kernel.print Pry::Helpers::BaseHelpers.windows_ansi? ? "\e[0F" : "\e[0G"
  end

  # Enter the matrix
  pry_instance.repl(head)
end

.view_clip(obj, max_length = 60) ⇒ String

An inspector that clips the output to max_length chars. In case of > max_length chars the `# notation is used.

Parameters:

  • obj

    The object to view.

  • max_length (defaults to: 60)

    The maximum number of chars before clipping occurs.

Returns:

  • (String)

    The string representation of obj.



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/pry/pry_class.rb', line 169

def self.view_clip(obj, max_length = 60)
  if obj.kind_of?(Module) && obj.name.to_s != "" && obj.name.to_s.length <= max_length
    obj.name.to_s
  elsif TOPLEVEL_BINDING.eval('self') == obj
    # special case for 'main' object :)
    obj.to_s
  elsif [String, Numeric, Symbol, nil, true, false].any? { |v| v === obj } && obj.inspect.length <= max_length
    obj.inspect
  else
    "#<#{obj.class}>"#:%x>"# % (obj.object_id << 1)
  end

rescue RescuableException
  "unknown"
end

.WrappedModule(obj) ⇒ Object

If the given object is a Pry::WrappedModule, return it unaltered. If it's anything else, return it wrapped in a Pry::WrappedModule instance.



7
8
9
10
11
12
13
# File 'lib/pry/wrapped_module.rb', line 7

def WrappedModule(obj)
  if obj.is_a? Pry::WrappedModule
    obj
  else
    Pry::WrappedModule.new(obj)
  end
end

Instance Method Details

#add_sticky_local(name) { ... } ⇒ Object

Add a sticky local to this Pry instance. A sticky local is a local that persists between all bindings in a session.

Parameters:

  • name (Symbol)

    The name of the sticky local.

Yields:

  • The block that defines the content of the local. The local will be refreshed at each tick of the repl loop.



176
177
178
# File 'lib/pry/pry_instance.rb', line 176

def add_sticky_local(name, &block)
  sticky_locals[name] = block
end

#current_contextBinding

The currently active Binding.

Returns:

  • (Binding)

    The currently active Binding for the session.



116
117
118
# File 'lib/pry/pry_instance.rb', line 116

def current_context
  binding_stack.last
end

#exec_hook(name, *args, &block) ⇒ Object, Exception

Execute the specified hook. If executing a hook raises an exception, we log that and then continue sucessfully. To debug such errors, use the global variable $pry_hook_error, which is set as a result.

Parameters:

  • name (Symbol)

    The hook name to execute

  • args (*Object)

    The arguments to pass to the hook

Returns:

  • (Object, Exception)

    The return value of the hook or the exception raised



474
475
476
477
478
479
480
481
482
483
# File 'lib/pry/pry_instance.rb', line 474

def exec_hook(name, *args, &block)
  e_before = hooks.errors.size
  hooks.exec_hook(name, *args, &block).tap do
    hooks.errors[e_before..-1].each do |e|
      output.puts "#{name} hook failed: #{e.class}: #{e.message}"
      output.puts "#{e.backtrace.first}"
      output.puts "(see _pry_.hooks.errors to debug)"
    end
  end
end

#generate_prompt(prompt_proc, conf) ⇒ Object (private)



655
656
657
658
659
660
661
# File 'lib/pry/pry_instance.rb', line 655

def generate_prompt(prompt_proc, conf)
  if prompt_proc.arity == 1
    prompt_proc.call(conf)
  else
    prompt_proc.call(conf.object, conf.nesting_level, conf._pry_)
  end
end

#handle_read_errorsObject (private)

Manage switching of input objects on encountering EOFErrors



540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
# File 'lib/pry/pry_instance.rb', line 540

def handle_read_errors
  should_retry = true
  exception_count = 0
  begin
    yield
  rescue EOFError
    if input_stack.empty?
      self.input = Pry.config.input
      if !should_retry
        output.puts "Error: Pry ran out of things to read from! Attempting to break out of REPL."
        throw(:breakout)
      end
      should_retry = false
    else
      self.input = input_stack.pop
    end

    retry

  # Interrupts are handled in r() because they need to tweak eval_string
  # TODO: Refactor this baby.
  rescue Interrupt
    raise

  # If we get a random error when trying to read a line we don't want to automatically
  # retry, as the user will see a lot of error messages scroll past and be unable to do
  # anything about it.
  rescue RescuableException => e
    puts "Error: #{e.message}"
    output.puts e.backtrace
    exception_count += 1
    if exception_count < 5
      retry
    end
    puts "FATAL: Pry failed to get user input using `#{input}`."
    puts "To fix this you may be able to pass input and output file descriptors to pry directly. e.g."
    puts "  Pry.config.input = STDIN"
    puts "  Pry.config.output = STDOUT"
    puts "  binding.pry"
    throw(:breakout)
  end
end

#inject_local(name, value, b) ⇒ Object

Injects a local variable into the provided binding.

Parameters:

  • name (String)

    The name of the local to inject.

  • value (Object)

    The value to set the local to.

  • b (Binding)

    The binding to set the local on.

Returns:

  • (Object)

    The value the local was set to.



145
146
147
148
149
150
# File 'lib/pry/pry_instance.rb', line 145

def inject_local(name, value, b)
  Thread.current[:__pry_local__] = value.is_a?(Proc) ? value.call : value
  b.eval("#{name} = ::Thread.current[:__pry_local__]")
ensure
  Thread.current[:__pry_local__] = nil
end

#inject_sticky_locals(target) ⇒ Object

Inject all the sticky locals into the target binding.

Parameters:

  • target (Binding)


165
166
167
168
169
# File 'lib/pry/pry_instance.rb', line 165

def inject_sticky_locals(target)
  sticky_locals.each_pair do |name, value|
    inject_local(name, value, target)
  end
end

#last_result_is_exception?Boolean

Returns True if the last result is an exception that was raised, as opposed to simply an instance of Exception (like the result of Exception.new).

Returns:

  • (Boolean)

    True if the last result is an exception that was raised, as opposed to simply an instance of Exception (like the result of Exception.new)



535
536
537
# File 'lib/pry/pry_instance.rb', line 535

def last_result_is_exception?
  @last_result_is_exception
end

#memory_sizeInteger

Returns The maximum amount of objects remembered by the inp and out arrays. Defaults to 100.

Returns:

  • (Integer)

    The maximum amount of objects remembered by the inp and out arrays. Defaults to 100.



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

def memory_size
  @output_array.max_size
end

#memory_size=(size) ⇒ Object



158
159
160
161
# File 'lib/pry/pry_instance.rb', line 158

def memory_size=(size)
  @input_array  = Pry::HistoryArray.new(size)
  @output_array = Pry::HistoryArray.new(size)
end

#pop_promptArray<Proc>

Pops the current prompt off of the prompt stack. If the prompt you are popping is the last prompt, it will not be popped. Use this to restore the previous prompt.

Examples:

prompt1 = [ proc { '>' }, proc { '>>' } ]
prompt2 = [ proc { '$' }, proc { '>' } ]
pry = Pry.new :prompt => prompt1
pry.push_prompt(prompt2)
pry.pop_prompt # => prompt2
pry.pop_prompt # => prompt1
pry.pop_prompt # => prompt1

Returns:

  • (Array<Proc>)

    Prompt being popped.



693
694
695
# File 'lib/pry/pry_instance.rb', line 693

def pop_prompt
  prompt_stack.size > 1 ? prompt_stack.pop : prompt
end

#process_command(val, eval_string, target) ⇒ Boolean

If the given line is a valid command, process it in the context of the current eval_string and context. This method should not need to be invoked directly.

Parameters:

  • val (String)

    The line to process.

  • eval_string (String)

    The cumulative lines of input.

  • target (Binding)

    The target of the Pry session.

Returns:

  • (Boolean)

    true if val is a command, false otherwise



422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
# File 'lib/pry/pry_instance.rb', line 422

def process_command(val, eval_string, target)
  result = commands.process_line(val, {
    :target => target,
    :output => output,
    :eval_string => eval_string,
    :pry_instance => self
  })

  # set a temporary (just so we can inject the value we want into eval_string)
  Thread.current[:__pry_cmd_result__] = result

  # note that `result` wraps the result of command processing; if a
  # command was matched and invoked then `result.command?` returns true,
  # otherwise it returns false.
  if result.command?
    if !result.void_command?
      # the command that was invoked was non-void (had a return value) and so we make
      # the value of the current expression equal to the return value
      # of the command.
      eval_string.replace "Thread.current[:__pry_cmd_result__].retval\n"
    end
    true
  else
    false
  end
end

#promptArray<Proc>

The current prompt. This is the prompt at the top of the prompt stack.

Examples:

self.prompt = Pry::SIMPLE_PROMPT
self.prompt # => Pry::SIMPLE_PROMPT

Returns:

  • (Array<Proc>)

    Current prompt.



128
129
130
# File 'lib/pry/pry_instance.rb', line 128

def prompt
  prompt_stack.last
end

#prompt=(new_prompt) ⇒ Object



132
133
134
135
136
137
138
# File 'lib/pry/pry_instance.rb', line 132

def prompt=(new_prompt)
  if prompt_stack.empty?
    push_prompt new_prompt
  else
    prompt_stack[-1] = new_prompt
  end
end

#prompt_stackObject (private)

the array that the prompt stack is stored in



665
666
667
# File 'lib/pry/pry_instance.rb', line 665

def prompt_stack
  @prompt_stack ||= Array.new
end

#push_prompt(new_prompt) ⇒ Array<Proc>

Pushes the current prompt onto a stack that it can be restored from later. Use this if you wish to temporarily change the prompt.

Examples:

new_prompt = [ proc { '>' }, proc { '>>' } ]
push_prompt(new_prompt) # => new_prompt

Parameters:

  • new_prompt (Array<Proc>)

Returns:

  • (Array<Proc>)

    new_prompt



677
678
679
# File 'lib/pry/pry_instance.rb', line 677

def push_prompt(new_prompt)
  prompt_stack.push new_prompt
end

#r(target = TOPLEVEL_BINDING, eval_string = "") ⇒ String

Perform a read. If no parameter is given, default to top-level (main). This is a multi-line read; so the read continues until a valid Ruby expression is received. Pry commands are also accepted here and operate on the target.

Examples:

Pry.new.r(Object.new)

Parameters:

  • target (Object, Binding) (defaults to: TOPLEVEL_BINDING)

    The receiver of the read.

  • eval_string (String) (defaults to: "")

    Optionally Prime eval_string with a start value.

Returns:

  • (String)

    The Ruby expression.



297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'lib/pry/pry_instance.rb', line 297

def r(target=TOPLEVEL_BINDING, eval_string="")
  target = Pry.binding_for(target)
  @suppress_output = false

  loop do
    begin
      # eval_string will probably be mutated by this method
      retrieve_line(eval_string, target)
    rescue CommandError, Slop::InvalidOptionError, MethodSource::SourceNotFoundError => e
      output.puts "Error: #{e.message}"
    end

    begin
      break if Pry::Code.complete_expression?(eval_string)
    rescue SyntaxError => e
      output.puts "SyntaxError: #{e.message.sub(/.*syntax error, */m, '')}"
      eval_string = ""
    end
  end

  @suppress_output = true if eval_string =~ /;\Z/ || eval_string.empty?

  exec_hook :after_read, eval_string, self
  eval_string
end

#raise_up(*args) ⇒ Object



736
# File 'lib/pry/pry_instance.rb', line 736

def raise_up(*args); raise_up_common(false, *args); end

#raise_up!(*args) ⇒ Object



737
# File 'lib/pry/pry_instance.rb', line 737

def raise_up!(*args); raise_up_common(true, *args); end

#raise_up_common(force, *args) ⇒ Object

Raise an exception out of Pry.

See Kernel#raise for documentation of parameters. See rb_make_exception for the inbuilt implementation.

This is necessary so that the raise-up command can tell the difference between an exception the user has decided to raise, and a mistake in specifying that exception.

(i.e. raise-up RunThymeError.new should not be the same as raise-up NameError, "unititialized constant RunThymeError")

Raises:

  • (TypeError)


709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
# File 'lib/pry/pry_instance.rb', line 709

def raise_up_common(force, *args)
  exception = if args == []
                last_exception || RuntimeError.new
              elsif args.length == 1 && args.first.is_a?(String)
                RuntimeError.new(args.first)
              elsif args.length > 3
                raise ArgumentError, "wrong number of arguments"
              elsif !args.first.respond_to?(:exception)
                raise TypeError, "exception class/object expected"
              elsif args.length === 1
                args.first.exception
              else
                args.first.exception(args[1])
              end

  raise TypeError, "exception object expected" unless exception.is_a? Exception

  exception.set_backtrace(args.length === 3 ? args[2] : caller(1))

  if force || binding_stack.one?
    binding_stack.clear
    throw :raise_up, exception
  else
    binding_stack.pop
    raise exception
  end
end

#re(target = TOPLEVEL_BINDING) ⇒ Object

Perform a read-eval If no parameter is given, default to top-level (main).

Examples:

Pry.new.re(Object.new)

Parameters:

  • target (Object, Binding) (defaults to: TOPLEVEL_BINDING)

    The receiver of the read-eval-print

Returns:

  • (Object)

    The result of the eval or an Exception object in case of error. In the latter case, you can check whether the exception was raised or is just the result of the expression using #last_result_is_exception?



264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/pry/pry_instance.rb', line 264

def re(target=TOPLEVEL_BINDING)
  target = Pry.binding_for(target)

  # It's not actually redundant to inject them continually as we may have
  # moved into the scope of a new Binding (e.g the user typed `cd`)
  inject_sticky_locals(target)

  code = r(target)

  exec_hook :before_eval, code, self

  result = target.eval(code, Pry.eval_path, Pry.current_line)
  set_last_result(result, target, code)

  result
rescue RescuableException => e
  self.last_exception = e
  e
ensure
  update_input_history(code)
  exec_hook :after_eval, result, self
end

#readline(current_prompt = "> ", completion_proc = nil) ⇒ String

Returns the next line of input to be used by the pry instance. This method should not need to be invoked directly.

Parameters:

  • current_prompt (String) (defaults to: "> ")

    The prompt to use for input.

Returns:

  • (String)

    The next line of input.



588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
# File 'lib/pry/pry_instance.rb', line 588

def readline(current_prompt="> ", completion_proc=nil)
  handle_read_errors do

    if defined? Coolline and input.is_a? Coolline
      input.completion_proc = proc do |cool|
        completion_proc.call cool.completed_word
      end
    elsif input.respond_to? :completion_proc=
      input.completion_proc = completion_proc
    end

    if input == Readline
      input.readline(current_prompt, false) # false since we'll add it manually
    elsif defined? Coolline and input.is_a? Coolline
      input.readline(current_prompt)
    else
      if input.method(:readline).arity == 1
        input.readline(current_prompt)
      else
        input.readline
      end
    end
  end
end

#refresh(options = {}) ⇒ Object

Refresh the Pry instance settings from the Pry class. Allows options to be specified to override settings from Pry class.

Parameters:

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

    The options to override Pry class settings for this instance.



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/pry/pry_instance.rb', line 95

def refresh(options={})
  defaults   = {}
  attributes = [
                 :input, :output, :commands, :print, :quiet,
                 :exception_handler, :hooks, :custom_completions,
                 :prompt, :memory_size, :input_stack, :extra_sticky_locals
               ]

  attributes.each do |attribute|
    defaults[attribute] = Pry.send attribute
  end

  defaults.merge!(options).each do |key, value|
    send("#{key}=", value) if respond_to?("#{key}=")
  end

  true
end

#rep(target = TOPLEVEL_BINDING) ⇒ Object

Perform a read-eval-print. If no parameter is given, default to top-level (main).

Examples:

Pry.new.rep(Object.new)

Parameters:

  • target (Object, Binding) (defaults to: TOPLEVEL_BINDING)

    The receiver of the read-eval-print



249
250
251
252
253
254
# File 'lib/pry/pry_instance.rb', line 249

def rep(target=TOPLEVEL_BINDING)
  target = Pry.binding_for(target)
  result = re(target)

  show_result(result) if should_print?
end

#repl(target = TOPLEVEL_BINDING) ⇒ Object

Start a read-eval-print-loop. If no parameter is given, default to top-level (main).

Examples:

Pry.new.repl(Object.new)

Parameters:

  • target (Object, Binding) (defaults to: TOPLEVEL_BINDING)

    The receiver of the Pry session

Returns:

  • (Object)

    The target of the Pry session or an explictly given return value. If given return value is nil or no return value is specified then target will be returned.



222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/pry/pry_instance.rb', line 222

def repl(target=TOPLEVEL_BINDING)
  target = Pry.binding_for(target)

  repl_prologue(target)

  break_data = nil
  exception = catch(:raise_up) do
    break_data = catch(:breakout) do
      loop do
        rep(binding_stack.last)
      end
    end
    exception = false
  end

  raise exception if exception

  break_data
ensure
  repl_epilogue(target)
end

#repl_epilogue(target) ⇒ Object

Clean-up after the repl session.

Parameters:

  • target (Binding)

    The target binding for the session.



207
208
209
210
211
212
# File 'lib/pry/pry_instance.rb', line 207

def repl_epilogue(target)
  exec_hook :after_session, output, target, self

  binding_stack.pop
  Pry.save_history if Pry.config.history.should_save
end

#repl_prologue(target) ⇒ Object

Initialize the repl session.

Parameters:

  • target (Binding)

    The target binding for the session.



195
196
197
198
199
200
201
202
203
# File 'lib/pry/pry_instance.rb', line 195

def repl_prologue(target)
  exec_hook :before_session, output, target, self
  set_last_result(nil, target)


  @input_array << nil # add empty input so _in_ and _out_ match

  binding_stack.push target
end

#retrieve_line(eval_string, target) ⇒ String

Read and process a line of input -- check for ^D, determine which prompt to use, rewrite the indentation if Pry.config.auto_indent is enabled, and, if the line is a command, process it and alter the eval_string accordingly. This method should not need to be invoked directly.

Parameters:

  • eval_string (String)

    The cumulative lines of input.

  • target (Binding)

    The target of the session.

Returns:

  • (String)

    The line received.



358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
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
# File 'lib/pry/pry_instance.rb', line 358

def retrieve_line(eval_string, target)
  @indent.reset if eval_string.empty?

  current_prompt = select_prompt(eval_string, target)
  completion_proc = Pry::InputCompleter.build_completion_proc(target,
                                                      instance_eval(&custom_completions))


  indentation = Pry.config.auto_indent ? @indent.current_prefix : ''

  begin
    val = readline("#{current_prompt}#{indentation}", completion_proc)

  # Handle <Ctrl+C> like Bash, empty the current input buffer but do not quit.
  # This is only for ruby-1.9; other versions of ruby do not let you send Interrupt
  # from within Readline.
  rescue Interrupt
    output.puts ""
    eval_string.replace("")
    return
  end

  # invoke handler if we receive EOF character (^D)
  if !val
    output.puts ""
    Pry.config.control_d_handler.call(eval_string, self)
    return
  end

  # Change the eval_string into the input encoding (Issue 284)
  # TODO: This wouldn't be necessary if the eval_string was constructed from
  # input strings only.
  if should_force_encoding?(eval_string, val)
    eval_string.force_encoding(val.encoding)
  end

  if Pry.config.auto_indent && !input.is_a?(StringIO)
    original_val = "#{indentation}#{val}"
    indented_val = @indent.indent(val)

    if output.tty? && Pry::Helpers::BaseHelpers.use_ansi_codes? && Pry.config.correct_indent
      output.print @indent.correct_indentation(current_prompt, indented_val, original_val.length - indented_val.length)
      output.flush
    end
  else
    indented_val = val
  end

  begin
    if !process_command(val, eval_string, target)
      eval_string << "#{indented_val.rstrip}\n" unless val.empty?
    end
  ensure
    Pry.history << indented_val unless input.is_a?(StringIO)
  end
end

#run_command(val, eval_string = "", target = binding_stack.last) ⇒ Pry::Command::VOID_VALUE

Run the specified command.

Examples:

pry_instance.run_command("ls -m")

Parameters:

  • val (String)

    The command (and its params) to execute.

  • eval_string (String) (defaults to: "")

    The current input buffer.

  • target (Binding) (defaults to: binding_stack.last)

    The binding to use..

Returns:



456
457
458
459
460
461
462
463
464
# File 'lib/pry/pry_instance.rb', line 456

def run_command(val, eval_string = "", target = binding_stack.last)
  commands.process_line(val,
    :eval_string => eval_string,
    :target => target,
    :pry_instance => self,
    :output => output
  )
  Pry::Command::VOID_VALUE
end

#select_prompt(eval_string, target) ⇒ String

Returns the appropriate prompt to use. This method should not need to be invoked directly.

Parameters:

  • eval_string (String)

    The current input buffer.

  • target (Binding)

    The target Binding of the Pry session.

Returns:

  • (String)

    The prompt.



626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
# File 'lib/pry/pry_instance.rb', line 626

def select_prompt(eval_string, target)
  target_self = target.eval('self')

  open_token = @indent.open_delimiters.any? ? @indent.open_delimiters.last :
    @indent.stack.last

  c = OpenStruct.new(
                     :object         => target_self,
                     :nesting_level  => binding_stack.size - 1,
                     :open_token     => open_token,
                     :session_line   => Pry.history.session_line_count + 1,
                     :history_line   => Pry.history.history_line_count + 1,
                     :expr_number    => input_array.count,
                     :_pry_          => self,
                     :binding_stack  => binding_stack,
                     :input_array    => input_array,
                     :eval_string    => eval_string,
                     :cont           => !eval_string.empty?)

  # If input buffer is empty then use normal prompt
  if eval_string.empty?
    generate_prompt(Array(prompt).first, c)

  # Otherwise use the wait prompt (indicating multi-line expression)
  else
    generate_prompt(Array(prompt).last, c)
  end
end

#set_last_result(result, target, code = "") ⇒ Object

Set the last result of an eval. This method should not need to be invoked directly.

Parameters:

  • result (Object)

    The result.

  • target (Binding)

    The binding to set _ on.

  • code (String) (defaults to: "")

    The code that was run.



490
491
492
493
494
495
# File 'lib/pry/pry_instance.rb', line 490

def set_last_result(result, target, code="")
  @last_result_is_exception = false
  @output_array << result

  self.last_result = result unless code =~ /\A\s*\z/
end

#should_force_encoding?(eval_string, val) ⇒ Boolean (private)

Returns:

  • (Boolean)


345
346
347
# File 'lib/pry/pry_instance.rb', line 345

def should_force_encoding?(eval_string, val)
  eval_string.empty? && val.respond_to?(:encoding) && val.encoding != eval_string.encoding
end

#should_print?Boolean

Whether the print proc should be invoked. Currently only invoked if the output is not suppressed OR the last result is an exception regardless of suppression.

Returns:

  • (Boolean)

    Whether the print proc should be invoked.



617
618
619
# File 'lib/pry/pry_instance.rb', line 617

def should_print?
  !@suppress_output || last_result_is_exception?
end

#show_result(result) ⇒ Object

Output the result or pass to an exception handler (if result is an exception).



324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# File 'lib/pry/pry_instance.rb', line 324

def show_result(result)
  if last_result_is_exception?
    exception_handler.call(output, result, self)
  else
    print.call(output, result)
  end
rescue RescuableException => e
  # Being uber-paranoid here, given that this exception arose because we couldn't
  # serialize something in the user's program, let's not assume we can serialize
  # the exception either.
  begin
    output.puts "(pry) output error: #{e.inspect}"
  rescue RescuableException => e
    if last_result_is_exception?
      output.puts "(pry) output error: failed to show exception"
    else
      output.puts "(pry) output error: failed to show result"
    end
  end
end

#sticky_localsHash

Returns The currently defined sticky locals.

Returns:

  • (Hash)

    The currently defined sticky locals.



181
182
183
184
185
186
187
188
189
190
191
# File 'lib/pry/pry_instance.rb', line 181

def sticky_locals
  @sticky_locals ||= {
    :_in_   => proc { @input_array },
    :_out_  => proc { @output_array },
    :_pry_  => self,
    :_ex_   => proc { last_exception },
    :_file_ => proc { last_file },
    :_dir_  => proc { last_dir },
    :_      => proc { last_result }
  }.merge(extra_sticky_locals)
end

#update_input_history(code) ⇒ Object

Update Pry's internal state after evalling code. This method should not need to be invoked directly.

Parameters:

  • code (String)

    The code we just eval'd



523
524
525
526
527
528
529
530
# File 'lib/pry/pry_instance.rb', line 523

def update_input_history(code)
  # Always push to the @input_array as the @output_array is always pushed to.
  @input_array << code
  if code
    Pry.line_buffer.push(*code.each_line)
    Pry.current_line += code.each_line.count
  end
end