class Prism::Dispatcher - Documentation for Ruby 4.1
Description: 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 type
Keywords: ruby,class,Prism::Dispatcher

🔍

No recent searches

# 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

listeners [R]

A hash mapping event names to arrays of listeners that should be notified when that event is fired.

### Public Class Methods

new ()
Source

    # File lib/prism/dispatcher.rb, line 56
    def initialize
      @listeners = {}
    end

Initialize a new dispatcher.

### Public Instance Methods

dispatch_once (node)
Source

    # File lib/prism/dispatcher.rb, line 88
    def dispatch_once(node)
      node.accept(DispatchOnce.new(listeners))
    end

Dispatches a single event for `node` to all registered listeners.

register (listener, *events)
Source

    # File lib/prism/dispatcher.rb, line 63
    def register(listener, *events)
      register_events(listener, events)
    end

Register a listener for one or more events.

register_public_methods (listener)
Source

    # File lib/prism/dispatcher.rb, line 71
    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)`.