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!

Like what you see? This is just a taste of RubyTapas! Sign up today to get two videos a week, along with full source code and transcripts. Or click here to learn more.
This entry was posted in Ruby, RubyTapas Samples, Screencasts and tagged , , , . Bookmark the permalink.
  • http://twitter.com/mrbrdo Jan Berdajs

    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.

    • http://avdi.org Avdi Grimm

      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!

      • http://twitter.com/mrbrdo Jan Berdajs

        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.

        • http://avdi.org Avdi Grimm

          Yeah I should have clarified that the resulting method is faster, not the creation of the method.

  • Pingback: The Last Week in Ruby: A Great Ruby Shirt, RSpec Team Changes and a Sneaky Segfault Trick

  • Roman

    You could also leverage the parameterized modules as in http://solnic.eu/2012/08/13/subclassing-module-for-fun-and-profit.html

    btw, the video overflows to the right.