class Prism::Dispatcher
The dispatcher class fires events for nodes that are found while walking an AST to all registered listeners. Itโs useful for performing different types of analysis on the AST while only having to walk the tree once.
To use the dispatcher, you would first instantiate it and register listeners for the events youโre interested in:
class OctalListener def on_integer_node_enter(node) if node.octal? && !node.slice.start_with?("0o") warn("Octal integers should be written with the 0o prefix") end end end listener = OctalListener.new dispatcher = Prism::Dispatcher.new dispatcher.register(listener, :on_integer_node_enter)
Then, you can walk any number of trees and dispatch events to the listeners:
result = Prism.parse("001 + 002 + 003") dispatcher.dispatch(result.value)
Optionally, you can also use dispatch_once to dispatch enter and leave events for a single node without recursing further down the tree. This can be useful in circumstances where you want to reuse the listeners you already have registers but want to stop walking the tree at a certain point.
integer = result.value.statements.body.first.receiver.receiver dispatcher.dispatch_once(integer)
Attributes
attr_reader listeners: Hash[Symbol, Array]
Public Class Methods
Source
# File lib/prism/dispatcher.rb, line 50 def initialize @listeners = {} end
Initialize a new dispatcher.
Public Instance Methods
Source
# File lib/prism/dispatcher.rb, line 74 def dispatch_once(node) node.accept(DispatchOnce.new(listeners)) end
Dispatches a single event for node to all registered listeners.
Source
# File lib/prism/dispatcher.rb, line 55 def register(listener, *events) register_events(listener, events) end
Register a listener for one or more events.
Source
# File lib/prism/dispatcher.rb, line 61 def register_public_methods(listener) register_events(listener, listener.public_methods(false).grep(/\Aon_.+_(?:enter|leave)\z/)) end
Register all public methods of a listener that match the pattern on_<node_name>_(enter|leave).