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
- Use
public_sendrather thansendunless you deliberately need to call a private method. - Avoid reopening core classes such as
StringorHash. If you need an extension, use a refinement or a small helper module. - Keep metaprogramming in one obvious place, such as a class method at the top of the class, rather than scattered through the file.
- Write a test for each generated method name, so a refactor that breaks the generator fails loudly.
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.