A class that provides the functionality of Kernel#set_trace_func
in a well-structured Object-Oriented API.
Use TracePoint
to gather information specifically for exceptions:
trace = TracePoint.new(:raise) do |tp| p [tp.lineno, tp.event, tp.raised_exception] end #=> #<TracePoint:disabled> trace.enable #=> false 0 / 0 #=> [5, :raise, #<ZeroDivisionError: divided by 0>]
If you don’t specify the types of events you want to listen for, TracePoint
will include all available events.
Note: Do not depend on the current event set, as this list is subject to change. Instead, it is recommended to specify the types of events you want to use.
To filter what is traced, you can pass any of the following as events
:
:line
Execute an expression or statement on a new line.
:class
Start a class or module definition.
:end
Finish a class or module definition.
:call
Call a Ruby
method.
:return
Return from a Ruby
method.
:c_call
Call a C-language routine.
:c_return
Return from a C-language routine.
:raise
Raise an exception.
:rescue
Rescue an exception.
:b_call
Event hook at block entry.
:b_return
Event hook at block ending.
:a_call
Event hook at all calls (call
, b_call
, and c_call
).
:a_return
Event hook at all returns (return
, b_return
, and c_return
).
:thread_begin
Event hook at thread beginning.
:thread_end
Event hook at thread ending.
:fiber_switch
Event hook at fiber switch.
:script_compiled
New Ruby
code compiled (with eval
, load
, or require
).
The Warning
module contains a single method named warn
, and the module extends itself, making Warning.warn
available. Warning.warn
is called for all warnings issued by Ruby
. By default, warnings are printed to $stderr.
Changing the behavior of Warning.warn
is useful to customize how warnings are handled by Ruby
, for instance by filtering some warnings, and/or outputting warnings somewhere other than $stderr
.
If you want to change the behavior of Warning.warn
you should use Warning.extend(MyNewModuleWithWarnMethod)
and you can use super
to get the default behavior of printing the warning to $stderr
.
Example:
module MyWarningFilter def warn(message, category: nil, **kwargs) if /some warning I want to ignore/.match?(message) # ignore else super end end end Warning.extend MyWarningFilter
You should never redefine Warning#warn
(the instance method), as that will then no longer provide a way to use the default behavior.
The warning gem provides convenient ways to customize Warning.warn
.
SingleForwardable
can be used to setup delegation at the object level as well.
printer = String.new printer.extend SingleForwardable # prepare object for delegation printer.def_delegator "STDOUT", "puts" # add delegation for STDOUT.puts() printer.puts "Howdy!"
Also, SingleForwardable
can be used to set up delegation for a Class
or Module
.
class Implementation def self.service puts "serviced!" end end module Facade extend SingleForwardable def_delegator :Implementation, :service end Facade.service #=> serviced!
If you want to use both Forwardable
and SingleForwardable
, you can use methods def_instance_delegator and def_single_delegator
, etc.
The Singleton
module implements the Singleton
pattern.
To use Singleton
, include the module in your class.
class Klass include Singleton # ... end
This ensures that only one instance of Klass can be created.
a,b = Klass.instance, Klass.instance a == b # => true Klass.new # => NoMethodError - new is private ...
The instance is created at upon the first call of Klass.instance().
class OtherKlass include Singleton # ... end ObjectSpace.each_object(OtherKlass){} # => 0 OtherKlass.instance ObjectSpace.each_object(OtherKlass){} # => 1
This behavior is preserved under inheritance and cloning.
This above is achieved by:
Making Klass.new and Klass.allocate private.
Overriding Klass.inherited(sub_klass) and Klass.clone() to ensure that the Singleton
properties are kept when inherited and cloned.
Providing the Klass.instance() method that returns the same object each time it is called.
Overriding Klass._load(str) to call Klass.instance().
Overriding Klass#clone and Klass#dup to raise TypeErrors to prevent cloning or duping.
Singleton
and Marshal
By default Singleton’s _dump(depth)
returns the empty string. Marshalling by default will strip state information, e.g. instance variables from the instance. Classes using Singleton
can provide custom _load(str) and _dump(depth) methods to retain some of the previous state of the instance.
require 'singleton' class Example include Singleton attr_accessor :keep, :strip def _dump(depth) # this strips the @strip information from the instance Marshal.dump(@keep, depth) end def self._load(str) instance.keep = Marshal.load(str) instance end end a = Example.instance a.keep = "keep this" a.strip = "get rid of this" stored_state = Marshal.dump(a) a.keep = nil a.strip = nil b = Marshal.load(stored_state) p a == b # => true p a.keep # => "keep this" p a.strip # => nil
Acts like a StringIO
with reduced API, but without having to require that class.
The original codebase emitted directly to $stderr, but now SyntaxError#detailed_message
needs a string output. To accomplish that we kept the original print infrastructure in place and added this class to accumulate the print output into a string.
Here we are going to patch StringQuery
to put in the class-level methods so that it can maintain a consistent interface
Query methods that allow categorizing strings based on their context for where they could be valid in a Ruby
syntax tree.
Helper methods for both Gem::Installer
and Gem::Uninstaller
This exception is raised if the nesting of parsed data structures is too deep.
The InstructionSequence
class represents a compiled sequence of instructions for the Virtual Machine used in MRI. Not all implementations of Ruby
may implement this class, and for the implementations that implement it, the methods defined and behavior of the methods can change in any version.
With it, you can get a handle to the instructions that make up a method or a proc, compile strings of Ruby
code down to VM instructions, and disassemble instruction sequences to strings for easy inspection. It is mostly useful if you want to learn how YARV works, but it also lets you control various settings for the Ruby
iseq compiler.
You can find the source for the VM instructions in insns.def
in the Ruby
source.
The instruction sequence results will almost certainly change as Ruby
changes, so example output in this documentation may be different from what you see.
Of course, this class is MRI specific.
Exception
raised when there is an invalid encoding detected
Response class for URI Too Long
responses (status code 414).
The URI
provided was too long for the server to process.
References:
PrettyPrint::SingleLine
is used by PrettyPrint.singleline_format
It is passed to be similar to a PrettyPrint
object itself, by responding to:
but instead, the output has no line breaks
Keeps track of what elements are in the queue in priority and also ensures that when one element engulfs/covers/eats another that the larger element evicts the smaller element
AbstractSyntaxTree
provides methods to parse Ruby
code into abstract syntax trees. The nodes in the tree are instances of RubyVM::AbstractSyntaxTree::Node
.
This module is MRI specific as it exposes implementation details of the MRI abstract syntax tree.
This module is experimental and its API is not stable, therefore it might change without notice. As examples, the order of children nodes is not guaranteed, the number of children nodes might change, there is no way to access children nodes by name, etc.
If you are looking for a stable API or an API working under multiple Ruby
implementations, consider using the prism gem, which is the official Ruby
API to parse Ruby
code.