class Pry

taken from irb Implements tab completion for Readline in Pry

{Pry::LastException} is a proxy class who wraps an Exception object for {Pry#last_exception}. it extends the exception object with methods that help pry commands be useful.

the original exception object is not modified and method calls are forwarded to the wrapped exception object.

A pager is an `IO`-like object that accepts text and either prints it immediately, prints it one page at a time, or streams it to an external program to print one page at a time.

rubocop:disable Metrics/ClassLength

Constants

BINDING_METHOD_IMPL

@return [Array] Code of the method used when implementing Pry's

__binding__, along with line indication to be used with instance_eval (and
friends).

@see Object#__binding__

Commands
EMPTY_COMPLETIONS
HAS_SAFE_LEVEL

@return [Boolean] true if this Ruby supports safe levels and tainting,

to guard against using deprecated or unsupported features
LOCAL_RC_FILE
VERSION

Attributes

cli[RW]
config[RW]
current_line[RW]
custom_completions[RW]
eval_path[RW]
last_internal_error[RW]
line_buffer[RW]
quiet[RW]
toplevel_binding[W]
backtrace[RW]
binding_stack[RW]
config[R]
custom_completions[RW]
eval_string[RW]
exit_value[R]
input_ring[R]

@since v0.12.0

last_dir[RW]
last_exception[R]
last_file[RW]
last_result[RW]
output_ring[R]

@since v0.12.0

suppress_output[RW]

Public Class Methods

Code(obj) click to toggle source

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

@param [Code, Method, UnboundMethod, Proc, Pry::Method, String, Array,

IO] obj
# File lib/pry/code.rb, line 12
def Code(obj)
  case obj
  when Code
    obj
  when ::Method, UnboundMethod, Proc, Pry::Method
    Code.from_method(obj)
  else
    Code.new(obj)
  end
end
Method(obj) click to toggle source

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

# File lib/pry/method.rb, line 9
def Method(obj)
  if obj.is_a? Pry::Method
    obj
  else
    Pry::Method.new(obj)
  end
end
WrappedModule(obj) click to toggle source

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

# 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
auto_resize!() click to toggle source
# File lib/pry/pry_class.rb, line 291
  def self.auto_resize!
    Pry.config.input # by default, load Readline

    if !defined?(Readline) || Pry.config.input != Readline
      warn "Sorry, you must be using Readline for Pry.auto_resize! to work."
      return
    end

    if Readline::VERSION =~ /edit/i
      warn(<<-WARN)
Readline version #{Readline::VERSION} detected - will not auto_resize! correctly.
  For the fix, use GNU Readline instead:
  https://github.com/guard/guard/wiki/Add-Readline-support-to-Ruby-on-Mac-OS-X
      WARN
      return
    end

    trap :WINCH do
      begin
        Readline.set_screen_size(*output.size)
      rescue StandardError => e
        warn "\nPry.auto_resize!'s Readline.set_screen_size failed: #{e}"
      end
      begin
        Readline.refresh_line
      rescue StandardError => e
        warn "\nPry.auto_resize!'s Readline.refresh_line failed: #{e}"
      end
    end
  end
binding_for(target) click to toggle source

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` @param [Object] target The object to get a `Binding` object for. @return [Binding] The `Binding` object.

# File lib/pry/pry_class.rb, line 346
def self.binding_for(target)
  return target if Binding === target # rubocop:disable Style/CaseEquality
  return TOPLEVEL_BINDING if Pry.main == target

  target.__binding__
end
configure() { |config| ... } click to toggle source

@example

Pry.configure do |config|
   config.eager_load! # optional
   config.input =     # ..
   config.foo = 2
end

@yield [config]

Yields a block with {Pry.config} as its argument.
# File lib/pry/pry_class.rb, line 48
def configure
  yield config
end
critical_section() { || ... } click to toggle source
# File lib/pry/pry_class.rb, line 379
def self.critical_section
  Thread.current[:pry_critical_section] ||= 0
  Thread.current[:pry_critical_section] += 1
  yield
ensure
  Thread.current[:pry_critical_section] -= 1
end
current() click to toggle source

@return [Pry::Config]

Returns a value store for an instance of Pry running on the current thread.
# File lib/pry/pry_class.rb, line 65
def self.current
  Thread.current[:__pry__] ||= {}
end
final_session_setup() click to toggle source
# File lib/pry/pry_class.rb, line 141
def self.final_session_setup
  return if @session_finalized

  @session_finalized = true
  load_plugins if Pry.config.should_load_plugins
  load_requires if Pry.config.should_load_requires
  load_history if Pry.config.history_load
  load_traps if Pry.config.should_trap_interrupts
  load_win32console if Helpers::Platform.windows? && !Helpers::Platform.windows_ansi?
end
in_critical_section?() click to toggle source
# File lib/pry/pry_class.rb, line 374
def self.in_critical_section?
  Thread.current[:pry_critical_section] ||= 0
  Thread.current[:pry_critical_section] > 0
end
init() click to toggle source

Basic initialization.

# File lib/pry/pry_class.rb, line 335
def self.init
  @plugin_manager ||= PluginManager.new
  reset_defaults
  locate_plugins
end
initial_session?() click to toggle source

@return [Boolean] Whether this is the first time a Pry session has

been started since loading the Pry class.
# File lib/pry/pry_class.rb, line 254
def self.initial_session?
  @initial_session
end
initial_session_setup() click to toggle source

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

# File lib/pry/pry_class.rb, line 131
def self.initial_session_setup
  return unless initial_session?

  @initial_session = false

  # note these have to be loaded here rather than in _pry_ as
  # we only want them loaded once per entire Pry lifetime.
  load_rc_files
end
load_file_at_toplevel(file) click to toggle source

Load the given file in the context of `Pry.toplevel_binding` @param [String] file The unexpanded file path.

# File lib/pry/pry_class.rb, line 71
def self.load_file_at_toplevel(file)
  toplevel_binding.eval(File.read(file), file)
rescue RescuableException => e
  puts "Error loading #{file}: #{e}\n#{e.backtrace.first}"
end
load_file_through_repl(file_name) click to toggle source

Execute the file through the REPL loop, non-interactively. @param [String] file_name File name to load through the REPL.

# File lib/pry/pry_class.rb, line 199
def self.load_file_through_repl(file_name)
  REPLFileLoader.new(file_name).load
end
load_history() click to toggle source

Load Readline history if required.

# File lib/pry/pry_class.rb, line 248
def self.load_history
  Pry.history.load
end
load_rc_files() click to toggle source

Load RC files if appropriate This method can also be used to reload the files if they have changed.

# File lib/pry/pry_class.rb, line 79
def self.load_rc_files
  rc_files_to_load.each do |file|
    critical_section do
      load_file_at_toplevel(file)
    end
  end
end
load_requires() click to toggle source

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

# File lib/pry/pry_class.rb, line 103
def self.load_requires
  Pry.config.requires.each do |file|
    require file
  end
end
load_traps() click to toggle source

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

# File lib/pry/pry_class.rb, line 111
def self.load_traps
  trap('INT') { raise Interrupt }
end
load_win32console() click to toggle source
# File lib/pry/pry_class.rb, line 115
  def self.load_win32console
    require 'win32console'
    # The mswin and mingw versions of pry require win32console, so this should
    # only fail on jruby (where win32console doesn't work).
    # Instead we'll recommend ansicon, which does.
  rescue LoadError
    warn <<-WARNING if Pry.config.windows_console_warning
For a better Pry experience on Windows, please use ansicon:
  https://github.com/adoxa/ansicon
If you use an alternative to ansicon and don't want to see this warning again,
you can add "Pry.config.windows_console_warning = false" to your pryrc.
    WARNING
  end
main() click to toggle source

@return [main]

returns the special instance of Object, "main".
# File lib/pry/pry_class.rb, line 57
def self.main
  @main ||= TOPLEVEL_BINDING.eval "self"
end
new(options = {}) click to toggle source

Create a new {Pry} instance. @param [Hash] options @option options [#readline] :input

The object to use for input.

@option options [#puts] :output

The object to use for output.

@option options [Pry::CommandBase] :commands

The object to use for commands.

@option options [Hash] :hooks

The defined hook Procs.

@option options [Pry::Prompt] :prompt

The array of Procs to use for prompts.

@option options [Proc] :print

The Proc to use for printing return values.

@option options [Boolean] :quiet

Omit the `whereami` banner when starting.

@option options [Array<String>] :backtrace

The backtrace of the session's `binding.pry` line, if applicable.

@option options [Object] :target

The initial context for this session.
# File lib/pry/pry_instance.rb, line 81
def initialize(options = {})
  @binding_stack = []
  @indent        = Pry::Indent.new(self)
  @eval_string   = ''.dup
  @backtrace     = options.delete(:backtrace) || caller
  target = options.delete(:target)
  @config = self.class.config.merge(options)
  push_prompt(config.prompt)
  @input_ring = Pry::Ring.new(config.memory_size)
  @output_ring = Pry::Ring.new(config.memory_size)
  @custom_completions = config.command_completions
  set_last_result nil
  @input_ring << nil
  push_initial_binding(target)
  exec_hook(:when_started, target, options, self)
  @prompt_warn = false
end
rc_files_to_load() click to toggle source

Load the local RC file (./.pryrc)

# File lib/pry/pry_class.rb, line 88
def self.rc_files_to_load
  files = []
  files << Pry.config.rc_file if Pry.config.should_load_rc
  files << LOCAL_RC_FILE if Pry.config.should_load_local_rc
  files.map { |file| real_path_to(file) }.compact.uniq
end
real_path_to(file) click to toggle source

Expand a file to its canonical name (following symlinks as appropriate)

# File lib/pry/pry_class.rb, line 96
def self.real_path_to(file)
  Pathname.new(File.expand_path(file)).realpath.to_s
rescue Errno::ENOENT, Errno::EACCES
  nil
end
reset_defaults() click to toggle source

Set all the configurable options back to their default values

# File lib/pry/pry_class.rb, line 323
def self.reset_defaults
  @initial_session = true
  @session_finalized = nil

  self.config = Pry::Config.new
  self.cli = false
  self.current_line = 1
  self.line_buffer = [""]
  self.eval_path = "(pry)"
end
run_command(command_string, options = {}) click to toggle source

Run a Pry command from outside a session. The commands available are those referenced by `Pry.config.commands` (the default command set). @param [String] command_string The Pry command (including arguments,

if any).

@param [Hash] options Optional named parameters. @return [nil] @option options [Object, Binding] :target The object to run the

command under. Defaults to `TOPLEVEL_BINDING` (main).

@option options [Boolean] :show_output Whether to show command

output. Defaults to true.

@example Run at top-level with no output.

Pry.run_command "ls"

@example Run under Pry class, returning only public methods.

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

@example Display command output.

Pry.run_command "ls -av", :show_output => true
# File lib/pry/pry_class.rb, line 274
def self.run_command(command_string, options = {})
  options = {
    target: TOPLEVEL_BINDING,
    show_output: true,
    output: Pry.config.output,
    commands: Pry.config.commands
  }.merge!(options)

  # :context for compatibility with <= 0.9.11.4
  target = options[:context] || options[:target]
  output = options[:show_output] ? options[:output] : StringIO.new

  pry = Pry.new(output: output, target: target, commands: options[:commands])
  pry.eval command_string
  nil
end
start(target = nil, options = {}) click to toggle source

Start a Pry REPL. This method also loads `pryrc` as necessary the first time it is invoked. @param [Object, Binding] target The receiver of the Pry session @param [Hash] options @option options (see Pry#initialize) @example

Pry.start(Object.new, :input => MyInput.new)
# File lib/pry/pry_class.rb, line 159
def self.start(target = nil, options = {})
  return if Pry::Env['DISABLE_PRY']
  if Pry::Env['FAIL_PRY']
    raise 'You have FAIL_PRY set to true, which results in Pry calls failing'
  end

  options = options.to_hash

  if in_critical_section?
    output.puts "ERROR: Pry started inside Pry."
    output.puts "This can happen if you have a binding.pry inside a #to_s " \
                "or #inspect function."
    return
  end

  options[:target] = Pry.binding_for(target || toplevel_binding)
  initial_session_setup
  final_session_setup

  # Unless we were given a backtrace, save the current one
  if options[:backtrace].nil?
    options[:backtrace] = caller

    # If Pry was started via `binding.pry`, elide that from the backtrace
    if options[:backtrace].first =~ /pry.*core_extensions.*pry/
      options[:backtrace].shift
    end
  end

  driver = options[:driver] || Pry::REPL

  # Enter the matrix
  driver.start(options)
rescue Pry::TooSafeException
  puts "ERROR: Pry cannot work with $SAFE > 0"
  raise
end
toplevel_binding() click to toggle source
# File lib/pry/pry_class.rb, line 353
  def self.toplevel_binding
    unless defined?(@toplevel_binding) && @toplevel_binding
      # Grab a copy of the TOPLEVEL_BINDING without any local variables.
      # This binding has a default definee of Object, and new methods are
      # private (just as in TOPLEVEL_BINDING).
      TOPLEVEL_BINDING.eval <<-RUBY
        def self.__pry__
          binding
        end
        Pry.toplevel_binding = __pry__
        class << self; undef __pry__; end
      RUBY
    end
    @toplevel_binding.eval('private')
    @toplevel_binding
  end
view_clip(obj, options = {}) click to toggle source

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

@param [Object] obj

The object to view.

@param [Hash] options @option options [Integer] :max_length (60)

The maximum number of chars before clipping occurs.

@option options [Boolean] :id (false)

Boolean to indicate whether or not a hex reprsentation of the object ID
is attached to the return value when the length of inspect is greater than
value of `:max_length`.

@return [String]

The string representation of `obj`.
# File lib/pry/pry_class.rb, line 222
def self.view_clip(obj, options = {})
  max = options.fetch :max_length, 60
  id = options.fetch :id, false
  if obj.is_a?(Module) && obj.name.to_s != "" && obj.name.to_s.length <= max
    obj.name.to_s
  elsif Pry.main == obj
    # Special-case to support jruby. Fixed as of:
    # https://github.com/jruby/jruby/commit/d365ebd309cf9df3dde28f5eb36ea97056e0c039
    # we can drop in the future.
    obj.to_s
    # rubocop:disable Style/CaseEquality
  elsif Pry.config.prompt_safe_contexts.any? { |v| v === obj } &&
        obj.inspect.length <= max
    # rubocop:enable Style/CaseEquality

    obj.inspect
  elsif id
    format("#<#{obj.class}:0x%<id>x>", id: obj.object_id << 1)
  else
    "#<#{obj.class}>"
  end
rescue RescuableException
  "unknown"
end

Public Instance Methods

add_sticky_local(name, &block) click to toggle source

Add a sticky local to this Pry instance. A sticky local is a local that persists between all bindings in a session. @param [Symbol] name The name of the sticky local. @yield The block that defines the content of the local. The local

will be refreshed at each tick of the repl loop.
# File lib/pry/pry_instance.rb, line 212
def add_sticky_local(name, &block)
  config.extra_sticky_locals[name] = block
end
complete(str) click to toggle source

Generate completions.

@param [String] str

What the user has typed so far

@return [Array<String>]

Possible completions
# File lib/pry/pry_instance.rb, line 145
def complete(str)
  return EMPTY_COMPLETIONS unless config.completer

  Pry.critical_section do
    completer = config.completer.new(config.input, self)
    completer.call(
      str,
      target: current_binding,
      custom_completions: custom_completions.call.push(*sticky_locals.keys)
    )
  end
end
current_binding() click to toggle source

The currently active `Binding`. @return [Binding] The currently active `Binding` for the session.

# File lib/pry/pry_instance.rb, line 124
def current_binding
  binding_stack.last
end
Also aliased as: current_context
current_context()
Alias for: current_binding
eval(line, options = {}) click to toggle source

Pass a line of input to Pry.

This is the equivalent of `Binding#eval` but with extra Pry!

In particular:

  1. Pry commands will be executed immediately if the line matches.

  2. Partial lines of input will be queued up until a complete expression has been accepted.

  3. Output is written to `#output` in pretty colours, not returned.

Once this method has raised an exception or returned false, this instance is no longer usable. {#exit_value} will return the session's breakout value if applicable.

@param [String?] line The line of input; `nil` if the user types `<Ctrl-D>` @option options [Boolean] :generated Whether this line was generated automatically.

Generated lines are not stored in history.

@return [Boolean] Is Pry ready to accept more input? @raise [Exception] If the user uses the `raise-up` command, this method

will raise that exception.
# File lib/pry/pry_instance.rb, line 255
def eval(line, options = {})
  return false if @stopped

  exit_value = nil
  exception = catch(:raise_up) do
    exit_value = catch(:breakout) do
      handle_line(line, options)
      # We use 'return !@stopped' here instead of 'return true' so that if
      # handle_line has stopped this pry instance (e.g. by opening pry_instance.repl and
      # then popping all the bindings) we still exit immediately.
      return !@stopped
    end
    exception = false
  end

  @stopped = true
  @exit_value = exit_value

  # TODO: make this configurable?
  raise exception if exception

  false
end
evaluate_ruby(code) click to toggle source
# File lib/pry/pry_instance.rb, line 286
def evaluate_ruby(code)
  inject_sticky_locals!
  exec_hook :before_eval, code, self

  result = current_binding.eval(code, Pry.eval_path, Pry.current_line)
  set_last_result(result, code)
ensure
  update_input_history(code)
  exec_hook :after_eval, result, self
end
exec_hook(name, *args, &block) click to toggle source

Execute the specified hook. @param [Symbol] name The hook name to execute @param [*Object] args The arguments to pass to the hook @return [Object, Exception] The return value of the hook or the exception raised

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.

# File lib/pry/pry_instance.rb, line 394
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.to_s
      output.puts "(see pry_instance.hooks.errors to debug)"
    end
  end
end
inject_local(name, value, binding) click to toggle source

Injects a local variable into the provided binding.

@param [String] name

The name of the local to inject.

@param [Object] value

The value to set the local to.

@param [Binding] binding

The binding to set the local on.

@return [Object]

The value the local was set to.
# File lib/pry/pry_instance.rb, line 173
def inject_local(name, value, binding)
  value = value.is_a?(Proc) ? value.call : value
  if binding.respond_to?(:local_variable_set)
    binding.local_variable_set name, value
  else # < 2.1
    begin
      Pry.current[:pry_local] = value
      binding.eval "#{name} = ::Pry.current[:pry_local]"
    ensure
      Pry.current[:pry_local] = nil
    end
  end
end
inject_sticky_locals!() click to toggle source

Inject all the sticky locals into the current binding.

# File lib/pry/pry_instance.rb, line 201
def inject_sticky_locals!
  sticky_locals.each_pair do |name, value|
    inject_local(name, value, current_binding)
  end
end
last_exception=(exception) click to toggle source

Set the last exception for a session. @param [Exception] exception The last exception.

# File lib/pry/pry_instance.rb, line 418
def last_exception=(exception)
  @last_result_is_exception = true
  last_exception = Pry::LastException.new(exception)
  @output_ring << last_exception
  @last_exception = last_exception
end
last_result_is_exception?() click to toggle source

@return [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)
# File lib/pry/pry_instance.rb, line 440
def last_result_is_exception?
  @last_result_is_exception
end
memory_size() click to toggle source

@return [Integer] The maximum amount of objects remembered by the inp and

out arrays. Defaults to 100
# File lib/pry/pry_instance.rb, line 190
def memory_size
  @output_ring.max_size
end
memory_size=(size) click to toggle source
# File lib/pry/pry_instance.rb, line 195
def memory_size=(size)
  @input_ring = Pry::Ring.new(size)
  @output_ring = Pry::Ring.new(size)
end
output() click to toggle source

Returns an output device @example

pry_instance.output.puts "ohai!"
# File lib/pry/pry_instance.rb, line 538
def output
  Pry::Output.new(self)
end
pager() click to toggle source

Returns the currently configured pager @example

pry_instance.pager.page text
# File lib/pry/pry_instance.rb, line 530
def pager
  Pry::Pager.new(self)
end
pop_prompt() click to toggle source

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.

@example

pry = Pry.new(prompt: Pry::Prompt[:my_prompt1])
pry.push_prompt(Pry::Prompt[:my_prompt2])
pry.pop_prompt # => prompt2
pry.pop_prompt # => prompt1
pry.pop_prompt # => prompt1

@return [Pry::Prompt] the prompt being popped

# File lib/pry/pry_instance.rb, line 522
def pop_prompt
  prompt_stack.size > 1 ? prompt_stack.pop : prompt
end
process_command(val) click to toggle source

If the given line is a valid command, process it in the context of the current `eval_string` and binding. @param [String] val The line to process. @return [Boolean] `true` if `val` is a command, `false` otherwise

# File lib/pry/pry_instance.rb, line 325
def process_command(val)
  val = val.lstrip if /^\s\S/ !~ val
  val = val.chomp
  result = commands.process_line(
    val,
    target: current_binding,
    output: output,
    eval_string: @eval_string,
    pry_instance: self,
    hooks: hooks
  )

  # set a temporary (just so we can inject the value we want into eval_string)
  Pry.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?
    unless 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 = "::Pry.current[:pry_cmd_result].retval\n"
    end
    true
  else
    false
  end
end
process_command_safely(val) click to toggle source

Same as process_command, but outputs exceptions to `#output` instead of raising. @param [String] val The line to process. @return [Boolean] `true` if `val` is a command, `false` otherwise

# File lib/pry/pry_instance.rb, line 360
def process_command_safely(val)
  process_command(val)
rescue CommandError,
       Pry::Slop::InvalidOptionError,
       MethodSource::SourceNotFoundError => e
  Pry.last_internal_error = e
  output.puts "Error: #{e.message}"
  true
end
prompt() click to toggle source

This is the prompt at the top of the prompt stack. @return [Pry::Prompt] the current prompt

# File lib/pry/pry_instance.rb, line 101
def prompt
  prompt_stack.last
end
prompt=(new_prompt) click to toggle source

Sets the Pry prompt. @param [Pry::Prompt] new_prompt @return [void]

# File lib/pry/pry_instance.rb, line 108
def prompt=(new_prompt)
  if prompt_stack.empty?
    push_prompt new_prompt
  else
    prompt_stack[-1] = new_prompt
  end
end
push_binding(object) click to toggle source

Push a binding for the given object onto the stack. If this instance is currently stopped, mark it as usable again.

# File lib/pry/pry_instance.rb, line 131
def push_binding(object)
  @stopped = false
  binding_stack << Pry.binding_for(object)
end
push_initial_binding(target = nil) click to toggle source

Initialize this instance by pushing its initial context into the binding stack. If no target is given, start at the top level.

# File lib/pry/pry_instance.rb, line 118
def push_initial_binding(target = nil)
  push_binding(target || Pry.toplevel_binding)
end
push_prompt(new_prompt) click to toggle source

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

@example

push_prompt(Pry::Prompt[:my_prompt])

@param [Pry::Prompt] new_prompt @return [Pry::Prompt] new_prompt

# File lib/pry/pry_instance.rb, line 506
def push_prompt(new_prompt)
  prompt_stack.push new_prompt
end
quiet?() click to toggle source

Convenience accessor for the `quiet` config key. @return [Boolean]

# File lib/pry/pry_instance.rb, line 592
def quiet?
  config.quiet
end
raise_up(*args) click to toggle source
# File lib/pry/pry_instance.rb, line 582
def raise_up(*args)
  raise_up_common(false, *args)
end
raise_up!(*args) click to toggle source
# File lib/pry/pry_instance.rb, line 586
def raise_up!(*args)
  raise_up_common(true, *args)
end
raise_up_common(force, *args) click to toggle source

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")
# File lib/pry/pry_instance.rb, line 554
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.size == 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.size == 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
repl(target = nil) click to toggle source

Potentially deprecated. Use `Pry::REPL.new(pry, :target => target).start` (If nested sessions are going to exist, this method is fine, but a goal is to come up with an alternative to nested sessions altogether.)

# File lib/pry/pry_instance.rb, line 282
def repl(target = nil)
  Pry::REPL.new(self, target: target).start
end
reset_eval_string() click to toggle source

Reset the current eval string. If the user has entered part of a multiline expression, this discards that input.

# File lib/pry/pry_instance.rb, line 231
def reset_eval_string
  @eval_string = ''.dup
end
run_command(val) click to toggle source

Run the specified command. @param [String] val The command (and its params) to execute. @return [Pry::Command::VOID_VALUE] @example

pry_instance.run_command("ls -m")
# File lib/pry/pry_instance.rb, line 375
def run_command(val)
  commands.process_line(
    val,
    eval_string: @eval_string,
    target: current_binding,
    pry_instance: self,
    output: output
  )
  Pry::Command::VOID_VALUE
end
select_prompt() click to toggle source

Returns the appropriate prompt to use. @return [String] The prompt.

# File lib/pry/pry_instance.rb, line 453
def select_prompt
  object = current_binding.eval('self')
  open_token = @indent.open_delimiters.last || @indent.stack.last

  c = OpenStruct.new(
    object: object,
    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_ring.count,
    pry_instance: self,
    binding_stack: binding_stack,
    input_ring: input_ring,
    eval_string: @eval_string,
    cont: !@eval_string.empty?
  )

  Pry.critical_section do
    # If input buffer is empty, then use normal prompt. Otherwise use the wait
    # prompt (indicating multi-line expression).
    if prompt.is_a?(Pry::Prompt)
      prompt_proc = eval_string.empty? ? prompt.wait_proc : prompt.incomplete_proc
      return prompt_proc.call(c.object, c.nesting_level, c.pry_instance)
    end

    unless @prompt_warn
      @prompt_warn = true
      Kernel.warn(
        "warning: setting prompt with help of " \
        "`Pry.config.prompt = [proc {}, proc {}]` is deprecated. " \
        "Use Pry::Prompt API instead"
      )
    end

    # 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
end
set_last_result(result, code = "") click to toggle source

Set the last result of an eval. This method should not need to be invoked directly. @param [Object] result The result. @param [String] code The code that was run.

# File lib/pry/pry_instance.rb, line 409
def set_last_result(result, code = "")
  @last_result_is_exception = false
  @output_ring << result

  self.last_result = result unless code =~ /\A\s*\z/
end
should_print?() click to toggle source

Whether the print proc should be invoked. Currently only invoked if the output is not suppressed. @return [Boolean] Whether the print proc should be invoked.

# File lib/pry/pry_instance.rb, line 447
def should_print?
  !@suppress_output
end
show_result(result) click to toggle source

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

# File lib/pry/pry_instance.rb, line 298
def show_result(result)
  if last_result_is_exception?
    exception_handler.call(output, result, self)
  elsif should_print?
    print.call(output, result, self)
  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}\n#{e.backtrace.join("\n")}"
  rescue RescuableException
    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
ensure
  output.flush if output.respond_to?(:flush)
end
sticky_locals() click to toggle source
# File lib/pry/pry_instance.rb, line 216
def sticky_locals
  {
    _in_: input_ring,
    _out_: output_ring,
    pry_instance: self,
    _ex_: last_exception && last_exception.wrapped_exception,
    _file_: last_file,
    _dir_: last_dir,
    _: proc { last_result },
    __: proc { output_ring[-2] }
  }.merge(config.extra_sticky_locals)
end
update_input_history(code) click to toggle source

Update Pry's internal state after evalling code. This method should not need to be invoked directly. @param [String] code The code we just eval'd

# File lib/pry/pry_instance.rb, line 428
def update_input_history(code)
  # Always push to the @input_ring as the @output_ring is always pushed to.
  @input_ring << code
  return unless code

  Pry.line_buffer.push(*code.each_line)
  Pry.current_line += code.lines.count
end

Private Instance Methods

ensure_correct_encoding!(val) click to toggle source

Force `eval_string` into the encoding of `val`. [Issue #284]

# File lib/pry/pry_instance.rb, line 680
def ensure_correct_encoding!(val)
  if @eval_string.empty? &&
     val.respond_to?(:encoding) &&
     val.encoding != @eval_string.encoding
    @eval_string.force_encoding(val.encoding)
  end
end
generate_prompt(prompt_proc, conf) click to toggle source
# File lib/pry/pry_instance.rb, line 688
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_instance)
  end
end
handle_line(line, options) click to toggle source
# File lib/pry/pry_instance.rb, line 598
def handle_line(line, options)
  if line.nil?
    config.control_d_handler.call(self)
    return
  end

  ensure_correct_encoding!(line)
  Pry.history << line unless options[:generated]

  @suppress_output = false
  inject_sticky_locals!
  begin
    unless process_command_safely(line)
      @eval_string += "#{line.chomp}\n" if !line.empty? || !@eval_string.empty?
    end
  rescue RescuableException => e
    self.last_exception = e
    result = e

    Pry.critical_section do
      show_result(result)
    end
    return
  end

  # This hook is supposed to be executed after each line of ruby code
  # has been read (regardless of whether eval_string is yet a complete expression)
  exec_hook :after_read, eval_string, self

  begin
    complete_expr = Pry::Code.complete_expression?(@eval_string)
  rescue SyntaxError => e
    output.puts e.message.gsub(/^.*syntax error, */, "SyntaxError: ")
    reset_eval_string
  end

  if complete_expr
    if @eval_string =~ /;\Z/ || @eval_string.empty? || @eval_string =~ /\A *#.*\n\z/
      @suppress_output = true
    end

    # A bug in jruby makes java.lang.Exception not rescued by
    # `rescue Pry::RescuableException` clause.
    #
    # * https://github.com/pry/pry/issues/854
    # * https://jira.codehaus.org/browse/JRUBY-7100
    #
    # Until that gets fixed upstream, treat java.lang.Exception
    # as an additional exception to be rescued explicitly.
    #
    # This workaround has a side effect: java exceptions specified
    # in `Pry.config.unrescued_exceptions` are ignored.
    jruby_exceptions = []
    jruby_exceptions << Java::JavaLang::Exception if Helpers::Platform.jruby?

    begin
      # Reset eval string, in case we're evaluating Ruby that does something
      # like open a nested REPL on this instance.
      eval_string = @eval_string
      reset_eval_string

      result = evaluate_ruby(eval_string)
    rescue RescuableException, *jruby_exceptions => e
      # Eliminate following warning:
      # warning: singleton on non-persistent Java type X
      # (http://wiki.jruby.org/Persistence)
      if Helpers::Platform.jruby? && e.class.respond_to?('__persistent__')
        e.class.__persistent__ = true
      end
      self.last_exception = e
      result = e
    end

    Pry.critical_section do
      show_result(result)
    end
  end

  throw(:breakout) if current_binding.nil?
end
prompt_stack() click to toggle source

the array that the prompt stack is stored in

# File lib/pry/pry_instance.rb, line 697
def prompt_stack
  @prompt_stack ||= []
end