Method_added macro without method parameter

Hi everyone, macro newbie here.

I was trying to use the method_added macro (as mentioned in the guides) but I kept running into an issue. I don’t seem to get the method name as a parameter in the macro call. Example:

class Example < ExampleBase
  def example_method
    # Whatever logic happens here
  end
end
abstract class ExampleBase
  macro inherited
    macro method_added(method)
      {% puts "Method added:", method.name.stringify %}
    end
  end
end

I would expect to get example_method as parameter but instead I get Error: undefined macro variable 'method'

I can’t seem to access the method names even with the following example:

abstract class ExampleBase
  macro inherited
    {% puts @type.methods %}
  end
end

All I see is an empty array in the console (no methods available?).

I also attempted to wrap the call with finished but didn’t get the subclass methods either (still empty arrays) with this:

abstract class ExampleBase
  macro inherited
    macro finished
      {% puts @type.methods %}
    end
  end
end

Does this mean I can’t access those subclass method names within the inherited macro hook? Did I overlook something (i.e. only works for modules and not classes) or is there another way to access these methods from the subclass on a macro hook?

FYI tested this with version 1.7.3

The main cause is that the macro expression evaluates in the scope of macro inherited. To move it to expand later in macro method_added (or macro finished), you can escape it:

abstract class ExampleBase
  macro inherited
    macro method_added(method)
      \{% puts "Method added:", method.name.stringify %}
    end
  end
end

This should give you the expected behaviour, I presume.

2 Likes

This did the trick. Thank you @straight-shoota