Back to Blog

Get in Touch

Ruby Quick Tip: Instant Utility Modules

By Michael Bleigh April 19, 2010 in ruby, quick tip

Missing

Sometimes you want to write a batch of utility methods that can be accessed from a module for example Utility.parse_something(string) or any number of useful little tools for your application. Here’s a very clean-looking way to achieve it:

module Utilities
  extend self

  def parse_something(string)
    # do stuff here
  end

  def other_utility_method(number, string)
    # do some more stuff
  end
end

By placing "extend self" at the top of the module, you are telling it to include all of the methods defined on your module as class methods on…your module. Which means that you can now access them like other class methods! While there are other ways to do this, I think this is a very semantically clean way that gets it done quite nicely.

Update: And this is exactly why I post these Quick Tips, because sometimes there’s another solution that I hadn’t heard of! Using Ruby’s module_function you can achieve the same effect:

module Utilities
  module_function
  
  def parse_something(string)
    # do stuff here
  end

  def other_utility_method(number, string)
    # do some more stuff
  end
end

The module_function method either takes multiple symbols as arguments for the methods to turn into module methods or, if invoked without arguments, will cause all subsequent methods to be defined as module functions. You can read the Ruby documentation about it here. Ultimately I’m not sure which I’d go with, as module_function is pretty esoteric (I’ve never come across it in code that I’ve read), but so is extend self. It’s your call, developers!

Tags:

ruby quick tip
Medium

Michael Bleigh

Michael has been with Intridea since 2007 and works to build Intridea's portfolio of products. With many years of experience working as both a designer and a developer, Michael specializes in helping to bridge the gap between the back-end development and the front-end design of a project. Michael is a prolific member of the Ruby on Rails community, having released popular open source libraries such as OmniAuth and spoken at conferences including RailsConf and RubyConf.

More posts by Michael Bleigh

Michael Bleigh

To the troubling idea isn't about what signal you're sending to your employee...

Michael Bleigh

Node.js has a pattern that I personally enjoy: if you require a directory, it...

Michael Bleigh

Last weekend I had the opportunity to speak at RubyConf 2012 about a topic th...