Class: Pry

Inherits:
Object show all
Extended by:
Forwardable
Defined in:
lib/pry/pry_class.rb,
lib/pry.rb,
lib/pry/config.rb,
lib/pry/plugins.rb,
lib/pry/version.rb,
lib/pry/commands.rb,
lib/pry/completion.rb,
lib/pry/command_set.rb,
lib/pry/pry_instance.rb,
lib/pry/helpers/text.rb,
lib/pry/history_array.rb,
lib/pry/command_context.rb,
lib/pry/command_processor.rb,
lib/pry/custom_completions.rb,
lib/pry/default_commands/ls.rb,
lib/pry/helpers/base_helpers.rb,
lib/pry/default_commands/gems.rb,
lib/pry/default_commands/input.rb,
lib/pry/default_commands/basic.rb,
lib/pry/default_commands/shell.rb,
lib/pry/helpers/command_helpers.rb,
lib/pry/default_commands/context.rb,
lib/pry/default_commands/easter_eggs.rb,
lib/pry/default_commands/documentation.rb,
lib/pry/default_commands/introspection.rb,
lib/pry/extended_commands/experimental.rb,
lib/pry/extended_commands/user_command_api.rb

Overview

Author:

Defined Under Namespace

Modules: DefaultCommands, ExtendedCommands, Helpers, InputCompleter Classes: CommandContext, CommandProcessor, CommandSet, Config, HistoryArray, NoCommandError, PluginManager

Constant Summary

DEFAULT_HOOKS =

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

{
  :before_session => proc do |out, target|
    # ensure we're actually in a method
    meth_name = target.eval('__method__')
    file = target.eval('__FILE__')

    # /unknown/ for rbx
    if file !~ /(\(.*\))|<.*>/ && file !~ /__unknown__/ && file != "" && file != "-e"
      Pry.run_command "whereami 5", :output => out, :show_output => true, :context => target, :commands => Pry::Commands
    end
  end
}
DEFAULT_PRINT =

The default prints

proc do |output, value|
  Helpers::BaseHelpers.stagger_output("=> #{Helpers::BaseHelpers.colorize_code(value.pretty_inspect)}", output)
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_PROMPT =

The default prompt; includes the target and nesting level

[
  proc { |target_self, nest_level|
    if nest_level == 0
      "pry(#{Pry.view_clip(target_self)})> "
    else
      "pry(#{Pry.view_clip(target_self)}):#{Pry.view_clip(nest_level)}> "
    end
  },

  proc { |target_self, nest_level|
    if nest_level == 0
      "pry(#{Pry.view_clip(target_self)})* "
    else
      "pry(#{Pry.view_clip(target_self)}):#{Pry.view_clip(nest_level)}* "
    end
  }
]
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} * " }
]
VERSION =
"0.9.1"
Commands =

Default commands used by Pry.

Pry::CommandSet.new do
  import DefaultCommands::Basic
  import DefaultCommands::Documentation
  import DefaultCommands::Gems
  import DefaultCommands::Context
  import DefaultCommands::Input
  import DefaultCommands::Shell
  import DefaultCommands::Introspection
  import DefaultCommands::EasterEggs
end
RC_FILES =

The RC Files to load.

["~/.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

- (Pry) initialize(options = {})

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' component of the REPL. (see print.rb)



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

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

  @command_processor = CommandProcessor.new(self)
end

Class Attribute Details

+ (Pry) active_instance

Get the active Pry instance that manages the active Pry session. This method should not need to be accessed directly.

Returns:

  • (Pry)

    The active Pry instance.



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

def active_instance
  @active_instance
end

+ (Boolean) cli

Whether Pry was activated from the command line.

Returns:

  • (Boolean)

    Whether Pry was activated from the command line.



66
67
68
# File 'lib/pry/pry_class.rb', line 66

def cli
  @cli
end

+ (Object) cmd_ret_value

Value returned by last executed Pry command.

Returns:

  • (Object)

    The command value



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

def cmd_ret_value
  @cmd_ret_value
end

+ (OpenStruct) config

Return Pry's config object.

Returns:

  • (OpenStruct)

    Return Pry's config object.



63
64
65
# File 'lib/pry/pry_class.rb', line 63

def config
  @config
end

+ (Fixnum) current_line

The current input line.

Returns:

  • (Fixnum)

    The current input line.



53
54
55
# File 'lib/pry/pry_class.rb', line 53

def current_line
  @current_line
end

+ (Proc) custom_completions

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



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

def custom_completions
  @custom_completions
end

+ (String) eval_path

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

Returns:

  • (String)

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



60
61
62
# File 'lib/pry/pry_class.rb', line 60

def eval_path
  @eval_path
end

+ (Exception) last_exception

Get last exception raised. This method should not need to be accessed directly.

Returns:

  • (Exception)

    The last exception.



34
35
36
# File 'lib/pry/pry_class.rb', line 34

def last_exception
  @last_exception
end

+ (Object) last_result

Get last value evaluated by Pry. This method should not need to be accessed directly.

Returns:

  • (Object)

    The last result.



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

def last_result
  @last_result
end

+ (Array) line_buffer

The Array of evaluated expressions.

Returns:

  • (Array)

    The Array of evaluated expressions.



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

def line_buffer
  @line_buffer
end

+ (Array) nesting (readonly)

Get nesting data. This method should not need to be accessed directly.

Returns:

  • (Array)

    The unparsed nesting information.



24
25
26
# File 'lib/pry/pry_class.rb', line 24

def nesting
  @nesting
end

Instance Attribute Details

- (Object) commands

Returns the value of attribute commands



7
8
9
# File 'lib/pry/pry_instance.rb', line 7

def commands
  @commands
end

- (Object) custom_completions

Returns the value of attribute custom_completions



11
12
13
# File 'lib/pry/pry_instance.rb', line 11

def custom_completions
  @custom_completions
end

- (Object) exception_handler

Returns the value of attribute exception_handler



9
10
11
# File 'lib/pry/pry_instance.rb', line 9

def exception_handler
  @exception_handler
end

- (Object) hooks

Returns the value of attribute hooks



10
11
12
# File 'lib/pry/pry_instance.rb', line 10

def hooks
  @hooks
end

- (Object) input

Returns the value of attribute input



5
6
7
# File 'lib/pry/pry_instance.rb', line 5

def input
  @input
end

- (Object) output

Returns the value of attribute output



6
7
8
# File 'lib/pry/pry_instance.rb', line 6

def output
  @output
end

Returns the value of attribute print



8
9
10
# File 'lib/pry/pry_instance.rb', line 8

def print
  @print
end

- (Binding) session_target

Returns the target binding for the session. Note that altering this attribute will not change the target binding.

Returns:

  • (Binding)

    The target object for the session



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

def session_target
  @session_target
end

Class Method Details

+ (Binding) binding_for(target)

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.



246
247
248
249
250
251
252
253
254
255
256
# File 'lib/pry/pry_class.rb', line 246

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

+ (Object) default_editor_for_platform



173
174
175
176
177
178
179
# File 'lib/pry/pry_class.rb', line 173

def self.default_editor_for_platform
  if RUBY_PLATFORM =~ /mswin|mingw/
    ENV['EDITOR'] ? ENV['EDITOR'] : "notepad"
  else
    ENV['EDITOR'] ? ENV['EDITOR'] : "nano"
  end
end

+ (Object) delegate_accessors(delagatee, *names)

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

+ (Object) init

Basic initialization.



221
222
223
224
225
226
227
# File 'lib/pry/pry_class.rb', line 221

def self.init
  @plugin_manager ||= PluginManager.new

  self.config ||= Config.new
  reset_defaults
  locate_plugins
end

+ (Boolean) initial_session?

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.



140
141
142
# File 'lib/pry/pry_class.rb', line 140

def self.initial_session?
  @initial_session
end

+ (Object) level



230
231
232
# File 'lib/pry/pry_class.rb', line 230

def @nesting.level
  last.is_a?(Array) ? last.first : nil
end

+ (Object) load_history

Load Readline history if required.



133
134
135
136
# File 'lib/pry/pry_class.rb', line 133

def self.load_history
  history_file = File.expand_path(Pry.config.history.file)
  Readline::HISTORY.push(*File.readlines(history_file).map(&:chomp)) if File.exists?(history_file)
end

+ (Object) load_rc

Load the rc files given in the Pry::RC_FILES array. Defaults to loading just ~/.pryrc. This method can also be used to reload the files if they have changed.



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

def self.load_rc
  RC_FILES.each do |file_name|
    file_name = File.expand_path(file_name)
    load(file_name) if File.exists?(file_name)
  end
end

+ (Object) reset_defaults

Set all the configurable options back to their default values



208
209
210
211
212
213
214
215
216
217
218
# File 'lib/pry/pry_class.rb', line 208

def self.reset_defaults
  set_config_defaults

  @initial_session = true

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

+ (Object) run_command(command_string, options = {})

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:

  • arg_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.



160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/pry/pry_class.rb', line 160

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]).rep(options[:context])
end

+ (Array<Pry>) sessions

Return all active Pry sessions.

Returns:

  • (Array<Pry>)

    Active Pry sessions.



236
237
238
239
# File 'lib/pry/pry_class.rb', line 236

def self.sessions
  # last element in nesting array is the pry instance
  nesting.map(&:last)
end

+ (Object) set_config_defaults



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/pry/pry_class.rb', line 181

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.hooks = DEFAULT_HOOKS
  config.color = true
  config.pager = true
  config.editor = default_editor_for_platform
  config.should_load_rc = true

  config.plugins ||= OpenStruct.new
  config.plugins.enabled = true
  config.plugins.strict_loading = true

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

  config.memory_size = 100
  config.results_pager = true
end

+ (Object) start(target = TOPLEVEL_BINDING, options = {})

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' component of the REPL. (see print.rb)



93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/pry/pry_class.rb', line 93

def self.start(target=TOPLEVEL_BINDING, options={})
  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, not
    # multiple times per each new session (i.e in debugging)
    load_rc if Pry.config.should_load_rc
    load_plugins if Pry.config.plugins.enabled
    load_history if Pry.config.history.should_load

    @initial_session = false
  end

  new(options).repl(target)
end

+ (String) view(obj)

A custom version of Kernel#pretty_inspect. This method should not need to be accessed directly.

Parameters:

  • obj

    The object to view.

Returns:

  • (String)

    The string representation of obj.



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

def self.view(obj)
  obj.pretty_inspect

rescue NoMethodError
  "unknown"
end

+ (String) view_clip(obj, max_size = 60)

A version of Pry.view that clips the output to max_size chars. In case of > max_size chars the `#<Object...> notation is used.

Parameters:

  • obj

    The object to view.

  • max_size (defaults to: 60)

    The maximum number of chars before clipping occurs.

Returns:

  • (String)

    The string representation of obj.



124
125
126
127
128
129
130
# File 'lib/pry/pry_class.rb', line 124

def self.view_clip(obj, max_size=60)
  if obj.inspect.size < max_size
    obj.inspect
  else
    "#<#{obj.class}:%#x>" % (obj.object_id << 1)
  end
end

Instance Method Details

- (Object) exec_hook(hook_name, *args, &block)

Execute the hook hook_name, if it is defined.

Parameters:

  • hook_name (Symbol)

    The hook to execute

  • args (Array)

    The arguments to pass to the hook.



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

def exec_hook(hook_name, *args, &block)
  hooks[hook_name].call(*args, &block) if hooks[hook_name]
end

- (Boolean) finished_top_level_session?

Whether top-level session has ended.

Returns:

  • (Boolean)

    Whether top-level session has ended.



102
103
104
# File 'lib/pry/pry_instance.rb', line 102

def finished_top_level_session?
  nesting.empty?
end

- (Boolean) last_result_is_exception?

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)



354
355
356
# File 'lib/pry/pry_instance.rb', line 354

def last_result_is_exception?
  @last_result_is_exception
end

- (Integer) memory_size

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.



78
79
80
# File 'lib/pry/pry_instance.rb', line 78

def memory_size
  @output_array.max_size
end

- (Object) memory_size=(size)



82
83
84
85
# File 'lib/pry/pry_instance.rb', line 82

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

- (Array) nesting

Get nesting data. This method should not need to be accessed directly.

Returns:

  • (Array)

    The unparsed nesting information.



90
91
92
# File 'lib/pry/pry_instance.rb', line 90

def nesting
  self.class.nesting
end

- (Object) nesting=(v)

Set nesting data. This method should not need to be accessed directly.

Parameters:

  • v

    nesting data.



97
98
99
# File 'lib/pry/pry_instance.rb', line 97

def nesting=(v)
  self.class.nesting = v
end

- (Boolean) null_input?(val)

Returns true if input is "" and a command is not returning a value.

Parameters:

  • val (String)

    The input string.

Returns:

  • (Boolean)

    Whether the input is null.



279
280
281
# File 'lib/pry/pry_instance.rb', line 279

def null_input?(val)
  val.empty? && !Pry.cmd_ret_value
end

- (Pry) parent

Return parent of current Pry session.

Returns:

  • (Pry)

    The parent of the current Pry session.



108
109
110
111
# File 'lib/pry/pry_instance.rb', line 108

def parent
  idx = Pry.sessions.index(self)
  Pry.sessions[idx - 1] if idx && idx > 0
end

- (Array<Proc>) pop_prompt

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.



444
445
446
# File 'lib/pry/pry_instance.rb', line 444

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

- (Object) process_line(val, eval_string, target)

Process the line received. 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.



306
307
308
309
310
311
312
313
314
315
# File 'lib/pry/pry_instance.rb', line 306

def process_line(val, eval_string, target)
  Pry.cmd_ret_value = @command_processor.process_commands(val, eval_string, target)

  if Pry.cmd_ret_value
    eval_string << "Pry.cmd_ret_value\n"
  else
    # only commands (with no ret_value) should have an empty `val` so this ignores their result
    eval_string << "#{val.rstrip}\n" if !val.empty?
  end
end

- (Array<Proc>) prompt

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.



64
65
66
# File 'lib/pry/pry_instance.rb', line 64

def prompt
  prompt_stack.last
end

- (Object) prompt=(new_prompt)



68
69
70
71
72
73
74
# File 'lib/pry/pry_instance.rb', line 68

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

- (Object) prompt_stack (private)

the array that the prompt stack is stored in



416
417
418
# File 'lib/pry/pry_instance.rb', line 416

def prompt_stack
  @prompt_stack ||= Array.new
end

- (Array<Proc>) push_prompt(new_prompt)

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



428
429
430
# File 'lib/pry/pry_instance.rb', line 428

def push_prompt(new_prompt)
  prompt_stack.push new_prompt
end

- (String) r(target = TOPLEVEL_BINDING, eval_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.



249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/pry/pry_instance.rb', line 249

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

  val = ""
  loop do
    val = retrieve_line(eval_string, target)
    process_line(val, eval_string, target)

    break if valid_expression?(eval_string)
  end

  @suppress_output = true if eval_string =~ /;\Z/ || null_input?(val)

  eval_string
end

- (Object) re(target = TOPLEVEL_BINDING)

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?



206
207
208
209
210
211
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/pry_instance.rb', line 206

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

  if input == Readline
    # Readline tab completion
    Readline.completion_proc = Pry::InputCompleter.build_completion_proc target, instance_eval(&custom_completions)
  end

  # save the pry instance to active_instance
  Pry.active_instance = self

  target.eval("inp = ::Pry.active_instance.instance_eval { @input_array }")
  target.eval("out = ::Pry.active_instance.instance_eval { @output_array }")

  @last_result_is_exception = false
  set_active_instance(target)

  code = r(target)

  Pry.line_buffer.push(*code.each_line)
  res = set_last_result(target.eval(code, Pry.eval_path, Pry.current_line), target)
  res
rescue SystemExit => e
  exit
rescue Exception => e
  @last_result_is_exception = true
  @output_array << e
  set_last_exception(e, target)
ensure
  @input_array << code
  Pry.current_line += code.each_line.count if code
end

- (String) readline(current_prompt = "> ")

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.



362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
# File 'lib/pry/pry_instance.rb', line 362

def readline(current_prompt="> ")

  if input == Readline

    # Readline must be treated differently
    # as it has a second parameter.
    input.readline(current_prompt, true)
  else
    begin
      if input.method(:readline).arity == 1
        input.readline(current_prompt)
      else
        input.readline
      end

    rescue EOFError
      self.input = Pry.input
      ""
    end
  end
end

- (Object) refresh(options = {})

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.



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/pry/pry_instance.rb', line 37

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

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

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

  true
end

- (Object) rep(target = TOPLEVEL_BINDING)

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



191
192
193
194
195
196
# File 'lib/pry/pry_instance.rb', line 191

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

  show_result(result) if should_print?
end

- (Object) repl(target = TOPLEVEL_BINDING)

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.



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/pry/pry_instance.rb', line 165

def repl(target=TOPLEVEL_BINDING)
  target = Pry.binding_for(target)
  target_self = target.eval('self')

  repl_prologue(target)

  # cannot rely on nesting.level as
  # nesting.level changes with new sessions
  nesting_level = nesting.size

  break_data = catch(:breakout) do
    nesting.push [nesting.size, target_self, self]
    loop do
      rep(target)
    end
  end

  return_value = repl_epilogue(target, nesting_level, break_data)
  return_value || target_self
end

- (Object) repl_epilogue(target, nesting_level, break_data)

Clean-up after the repl session.

Parameters:

  • target (Binding)

    The target binding for the session.

Returns:

  • (Object)

    The return value of the repl session (if one exists).



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/pry/pry_instance.rb', line 140

def repl_epilogue(target, nesting_level, break_data)
  nesting.pop
  exec_hook :after_session, output, target

  # If break_data is an array, then the last element is the return value
  break_level, return_value = Array(break_data)

  # keep throwing until we reach the desired nesting level
  if nesting_level != break_level
    throw :breakout, break_data
  end

  save_history if Pry.config.history.should_save && finished_top_level_session?

  return_value
end

- (Object) repl_prologue(target)

Initialize the repl session.

Parameters:

  • target (Binding)

    The target binding for the session.



122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/pry/pry_instance.rb', line 122

def repl_prologue(target)
  exec_hook :before_session, output, target
  Pry.active_instance = self

  # Make sure special locals exist
  target.eval("inp  = ::Pry.active_instance.instance_eval { @input_array }")
  target.eval("out = ::Pry.active_instance.instance_eval { @output_array }")

  set_active_instance(target)
  @input_array << nil # add empty input so inp and out match
  set_last_result(Pry.last_result, target)

  self.session_target = target
end

- (String) retrieve_line(eval_string, target)

Read a line of input and check for ^d, also determine prompt to use. 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.



288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/pry/pry_instance.rb', line 288

def retrieve_line(eval_string, target)
  current_prompt = select_prompt(eval_string.empty?, target.eval('self'))
  val = readline(current_prompt)

  # exit session if we receive EOF character
  if !val
    output.puts
    throw(:breakout, nesting.level)
  end

  val
end

- (Object) save_history

Save readline history to a file.



393
394
395
396
397
398
# File 'lib/pry/pry_instance.rb', line 393

def save_history
  history_file = File.expand_path(Pry.config.history.file)
  File.open(history_file, 'w') do |f|
    f.write Readline::HISTORY.to_a.join("\n")
  end
end

- (String) select_prompt(first_line, target_self)

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

Parameters:

  • first_line (Boolean)

    Whether this is the first line of input (and not multi-line input).

  • target_self (Object)

    The receiver of the Pry session.

Returns:

  • (String)

    The prompt.



406
407
408
409
410
411
412
413
# File 'lib/pry/pry_instance.rb', line 406

def select_prompt(first_line, target_self)

  if first_line
    Array(prompt).first.call(target_self, nesting.level)
  else
    Array(prompt).last.call(target_self, nesting.level)
  end
end

- (Object) set_active_instance(target)

Set the active instance for a session. This method should not need to be invoked directly.

Parameters:

  • target (Binding)

    The binding to set _ex_ on.



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

def set_active_instance(target)
  Pry.active_instance = self
  target.eval("_pry_ = ::Pry.active_instance")
end

- (Object) set_last_exception(ex, target)

Set the last exception for a session. This method should not need to be invoked directly.

Parameters:

  • ex (Exception)

    The exception.

  • target (Binding)

    The binding to set _ex_ on.



331
332
333
334
335
336
337
338
339
340
341
# File 'lib/pry/pry_instance.rb', line 331

def set_last_exception(ex, target)
  class << ex
    attr_accessor :file, :line
  end

  ex.backtrace.first =~ /(.*):(\d+)/
  ex.file, ex.line = $1, $2.to_i

  Pry.last_exception = ex
  target.eval("_ex_ = ::Pry.last_exception")
end

- (Object) set_last_result(result, target)

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.



321
322
323
324
325
# File 'lib/pry/pry_instance.rb', line 321

def set_last_result(result, target)
  Pry.last_result = result
  @output_array << result
  target.eval("_ = ::Pry.last_result")
end

- (Boolean) should_print?

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.



388
389
390
# File 'lib/pry/pry_instance.rb', line 388

def should_print?
  !@suppress_output || last_result_is_exception?
end

- (Object) show_result(result)

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



267
268
269
270
271
272
273
# File 'lib/pry/pry_instance.rb', line 267

def show_result(result)
  if last_result_is_exception?
    exception_handler.call output, result
  else
    print.call output, result
  end
end

- (Boolean) valid_expression?(code)

Determine if a string of code is a valid Ruby expression. Ruby 1.9 uses Ripper, Ruby 1.8 uses RubyParser.

Examples:

valid_expression?("class Hello") #=> false
valid_expression?("class Hello; end") #=> true

Parameters:

  • code (String)

    The code to validate.

Returns:

  • (Boolean)

    Whether or not the code is a valid Ruby expression.



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

def valid_expression?(code)
  RubyParser.new.parse(code)
  true
rescue Racc::ParseError, SyntaxError
  false
end