website logo

← All articles

Ruby Metaprogramming Adventures: playing the AST with Prism and runtime method decoration

I love Ruby. Not just for the syntax, but for the fact that you can sit down with a coffee during a Christmas vacation, wonder what if I could just declare that a method should skip its failing steps?, and actually build it. That's the kind of fun I want to tell you about.

Here’s the itch. You have a method that orchestrates a few tasks:

def do_work
  first_task
  second_task
  third_task
end

Normal Ruby: second_task raises, everything halts, third_task never runs. You either wrap every call in begin/rescue, or you wrap the whole method and lose per-task granularity.

I wanted to write this instead:

skip_failing_task_for :do_work

def do_work
  first_task
  second_task
  third_task
end

And have it work ie. treating the three methods as a set rather than a sequence. The macro declaration comes before the method even exists. That’s the fun part, ruby allows to make complex things quite simple on the surface. And this is where Ruby’s method_added hook stops being an obscure exotic method and starts being a genuinely useful play toy for us; and where Prism, Ruby’s new parser released a few days ago, gives us the missing piece when it comes to look up the internal structure of things that make a Ruby program.

Let’s build it step by step.

The Scope Restriction (Very important)

I want to state this upfront, because this is the difference between “cool experiment” and “thing you ship.”

We’re going to assume:

  • The wrapper method body is only a flat sequence of bare method calls.
  • No conditionals, no loops, no blocks, no yield, no dynamic dispatch, no arguments.
  • Each call resolves to another instance method on the same object.

That’s a real limitation. Once conditionals enter, “the set of tasks” becomes a control flow graph. Once send or method_missing enters, the list is invisible to any static analysis. The restriction buys us exactly what we need: a body we can enumerate. Within that box, the implementation is clean, correct, and genuinely satisfying to watch run.

The Hook That Makes It Possible

Ruby calls method_added on a class whenever an instance method is defined on it. So skip_failing_task_for just records the target name, and method_added does the heavy lifting when the definition finally lands:

def method_added(name)
  super
  return if @_wrapping
  pending = @_pending_skip
  return unless pending&.include?(name)
  # ... do the wrapping
end

Two details matter here.

The @_wrapping guard is mandatory. When we later call define_method(name) to replace the original, method_added fires again for name. Without a guard, that’s infinite recursion and a SystemStackError. It’s the kind of thing that looks obvious in a blog post and bites you during the play.

The @_pending_skip check ensures we only act on the method we were told about, not every definition that follows.

Extracting the Task List with Prism

Here’s where it gets genuinely exciting. Once method_added fires for do_work, we know the original exists and can ask Ruby where it came from:

file, line = instance_method(method_name).source_location

Then we parse the file with Prism and walk the AST to find the DefNode at that line. Prism’s own NodeFind module uses exactly this approach ie. matching DefNode by name and start line. From its body, we collect every bare CallNode:

def extract_task_calls(method_name)
  file, line = instance_method(method_name).source_location
  source = File.read(file)
  ast = Prism.parse(source).value

  def_node = find_def_at(ast, line)
  raise "Could not locate def for #{method_name}" unless def_node

  collect_bare_calls(def_node.body)
end

def find_def_at(node, target_line)
  return nil unless node
  return node if node.is_a?(Prism::DefNode) && node.location.start_line == target_line

  node.compact_child_nodes.each do |child|
    found = find_def_at(child, target_line)
    return found if found
  end
  nil
end

def collect_bare_calls(body)
  return [] unless body
  stmts = body.is_a?(Prism::StatementsNode) ? body.body : [body]
  stmts.filter_map do |stmt|
    next unless stmt.is_a?(Prism::CallNode)
    next if stmt.receiver
    next if stmt.arguments&.arguments&.any?
    stmt.name
  end
end

instance_method(name).source_location returns the file and starting line of the definition. Because method_added fires before we redefine anything, that location points at the original def do_work, which is exactly what we want. Prism’s visitor pattern makes the AST walk feel natural; the official Ruby repo has a whole sample dedicated to finding calls with Prism.

The receiver check is what enforces our scope. A bare call like first_task has no receiver. self.first_task or obj.first_task do, and they get excluded. It’s a feature, not a bug: the extractor never silently produces a list it can’t faithfully reproduce.

Redefining the Method

Now we replace do_work with a version that runs each extracted task independently:

def redefine_with_rescue(method_name, tasks)
  define_method(method_name) do |*args, **kwargs, &block|
    tasks.each do |task|
      begin
        public_send(task)
      rescue => e
        warn "[skip_failing_task_for] #{self.class}##{method_name}: " \
             "skipped #{task} (#{e.class}: #{e.message})"
      end
    end
    nil
  end
end

The @_wrapping flag set by the caller prevents method_added from recursing. The tasks array was captured lexically at definition time, so we don’t do any AST work at call time. That’s the price of parsing is paid once per method, at definition.

The Complete Implementation

require "prism"

module SkipFailingTask
  def skip_failing_task_for(method_name)
    (@_pending_skip ||= []) << method_name
  end

  def method_added(name)
    super
    return if @_wrapping
    pending = @_pending_skip
    return unless pending&.include?(name)

    @_wrapping = true
    begin
      tasks = extract_task_calls(name)
      redefine_with_rescue(name, tasks)
    ensure
      @_wrapping = false
      @_pending_skip.delete(name)
    end
  end

  private

  def extract_task_calls(method_name)
    file, line = instance_method(method_name).source_location
    source = File.read(file)
    ast = Prism.parse(source).value

    def_node = find_def_at(ast, line)
    raise "Could not locate def for #{method_name}" unless def_node

    collect_bare_calls(def_node.body)
  end

  def find_def_at(node, target_line)
    return nil unless node
    return node if node.is_a?(Prism::DefNode) && node.location.start_line == target_line

    node.compact_child_nodes.each do |child|
      found = find_def_at(child, target_line)
      return found if found
    end
    nil
  end

  def collect_bare_calls(body)
    return [] unless body
    stmts = body.is_a?(Prism::StatementsNode) ? body.body : [body]
    stmts.filter_map do |stmt|
      next unless stmt.is_a?(Prism::CallNode)
      next if stmt.receiver
      next if stmt.arguments&.arguments&.any?
      stmt.name
    end
  end

  def redefine_with_rescue(method_name, tasks)
    define_method(method_name) do |*args, **kwargs, &block|
      tasks.each do |task|
        begin
          public_send(task)
        rescue => e
          warn "[skip_failing_task_for] #{self.class}##{method_name}: " \
               "skipped #{task} (#{e.class}: #{e.message})"
        end
      end
      nil
    end
  end
end

Let’s Watch It Run

class Worker
  extend SkipFailingTask

  skip_failing_task_for :do_work

  def do_work
    first_task
    second_task
    third_task
  end

  def first_task
    puts "first"
  end

  def second_task
    raise "boom"
  end

  def third_task
    puts "third"
  end
end

Worker.new.do_work

Output:

first
[skip_failing_task_for] Worker#do_work: skipped second_task (RuntimeError: boom)
third

Exactly the “task set” semantics we wanted. Each task runs in isolation, failures are logged with the task name and exception, and the rest proceed. No manual begin/rescue scaffolding. Just a declaration.

Where This Beautiful Thing Breaks

If I’m claiming technical mastery, the honest part is knowing the boundary. This implementation is correct only under the stated restriction. The moment any of the following appears, the task list is silently wrong:

  • Conditionals or loops: the “list of calls” is no longer flat. You’d need to walk and preserve the AST, not just extract a list.
  • Dynamic dispatch: send(:dynamic_task), method_missing, define_method at runtime: all invisible to any static analysis.
  • Blocks and yield: the call surface is opaque at parse time.
  • Nested calls: first_task(second_task) produces a single CallNode for first_task; second_task lives in the arguments and won’t be in the list.
  • Metaprogrammed or eval-defined methods: source_location may return nil or point at a string, and the parse-and-read-file step fails.

None of these are fixable within our scope. They’re the reason I would not ship this as-is and this remains only a cool afternoon experiment

Why It Was Worth Building Anyway

Metaprogramming experiments like this are valuable for a specific reason: they locate the exact boundary of the language’s reflective surface. Ruby’s method_added hook lets us intercept a definition. Prism lets us inspect source and the code structure. Put together, they can build a real, working DSL for a non-trivial class of methods.

The value isn’t in shipping the edge idea. It’s in knowing precisely where the edge is, and being able to articulate exactly what it would take to move it a few inches further, without pretending those inches have necessarily any practical value.

That’s the kind of afternoon I enjoy on my spare time. Grab a coffee, open a REPL and the IDE, and build something slightly ridiculous. You’ll always learn more about Ruby in an afternoon by getting your hands dirty, than in a week of just reading the docs.