RubyTapas 027: Macros and Modules

In this episode themed after a certain sci-fi television series with the initials “BSG”, we take a look at how to use dynamically generated modules to make metaprogrammed methods open for future extension.

This is a two-parter. In part two, (which current subscribers received yesterday), we dig deeper and explore ways to make the generated modules more self-contained, self-explanatory, and discoverable. Part one is below; for part two, you’ll have to subscribe!


[boilerplate bypath=”rubytapas-sample”]


  1. The only thing I don’t like is that you use string eval. I thought that was bad practice. For some reason I really prefer the block format & define_method. I think the performance is probably better and it’s probably more likely to work with something like mruby. I think you could also probably avoid the block overhead (captured scope) with playing by using public_method instead of passing a block, but that’s nit-picking 🙂 Just a thought, anyway.

    1. I think you’ll find if you profile that string eval is more performant than define_method 🙂

      …but that’s not why I used it. I agree with you: I prefer define_method over string eval. I chose string eval here because I was trying to keep the focus on the module generation technique, and in my experience more devs understand string eval than understand define_method. So I was trying to keep the less important parts of the example as familiar as possible.

      Thanks for the feedback!

      1. Ah interesting. I think you probably mean that the execution of the method is faster when evaling a string, right? That makes sense, since it has to run a block when you do the block format. But I think it could be avoided too, like I mentioned, with public_method or similar. When I said more performant I meant only the defining of the method (how long it takes module_eval to complete), haven’t profiled it but it would make sense that it’s faster in block form since it’s already compiled to bytecode when the file is parsed (in YARV).
        But anyway I understand your reasoning, yeah.

Leave a Reply

Your email address will not be published. Required fields are marked *