Home / Womply Ruby Style Guide

Ruby Metaprogramming Style: Using define_method and method_missing Responsibly

The documentation that used to be at this address is no longer published, and its source was never released under an open license, so it is not reproduced here. This page is an independent guide to the same topic, written for this archive. It is not the project's documentation and is not affiliated with its authors.

Metaprogramming lets Ruby code write code. It powers much of what makes Rails pleasant, and it is also the fastest way to make a codebase impossible to search. A style guide should not ban it, but it should make the trade off explicit.

Start with plain methods

If you only need three similar methods, write three methods. Duplication that a reader can find with a text search is cheaper than a loop that generates methods nobody can grep for.

Prefer define_method over string eval

When you do generate methods, use define_method with a block. It is checked by the parser, it keeps a proper backtrace and it cannot be hijacked by unexpected input the way class_eval with a string can.

class Report
  FORMATS = %i[csv json pdf].freeze

  FORMATS.each do |format|
    define_method("to_#{format}") do
      Exporter.new(self, format: format).call
    end
  end
end

If you must use string class_eval for performance reasons, pass __FILE__ and __LINE__ so errors point somewhere useful, and add a comment showing what the generated code looks like.

method_missing needs a partner

Whenever you override method_missing, also define respond_to_missing?. Without it, respond_to? lies and tools such as method break. Always call super for names you do not handle.

class Settings
  def initialize(values)
    @values = values
  end

  def method_missing(name, *args)
    key = name.to_s
    return @values.fetch(key) if @values.key?(key)

    super
  end

  def respond_to_missing?(name, include_private = false)
    @values.key?(name.to_s) || super
  end
end

Other rules worth adopting

A quick test

Before merging metaprogrammed code, ask whether a new teammate could find where a method is defined in under a minute. If the answer is no, add a comment, or write the plain version.

More on Womply Ruby Style Guide

Explore the archive