O'Reilly logo

Ruby Cookbook by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

10.10. Avoiding Boilerplate Code with Metaprogramming

Problem

You've got to type in a lot of repetitive code that a trained monkey could write. You're resentful at having to do this yourself, and angry that the repetitive code will clutter up your class listings.

Solution

Ruby is happy to be the trained monkey that writes your repetitive code. You can define methods algorithmically with Module#define_method.

Usually the repetitive code is a bunch of similar methods. Suppose you need to write code like this:

	class Fetcher
	  def fetch(how_many)
	    puts "Fetching #{how_many ? how_many : "all"}."
	  end
	  def fetch_one
	    fetch(1)
	  end

	  def fetch_ten
	   fetch(10)
	  end

	  def fetch_all
	    fetch(nil)
	  end
	end

You can define this exact same code without having to write it all out. Create a data structure that contains the differences between the methods, and iterate over that structure, defining a method each time with define_method.

	class GeneratedFetcher
	  def fetch(how_many)
	    puts "Fetching #{how_many ? how_many : "all"}."
	  end

	  [["one", 1], ["ten", 10], ["all", nil]].each do |name, number|
	    define_method("fetch_#{name}") do
	      fetch(number)
	    end
	  end
	end

	GeneratedFetcher.instance_methods - Object.instance_methods
	# => ["fetch_one", "fetch", "fetch_ten", "fetch_all"]

	GeneratedFetcher.new.fetch_one
	# Fetching 1.

	GeneratedFetcher.new.fetch_all
	# Fetching all.

This is less to type, less monkeyish, and it takes up less space in your class listing. If you need to define more of these methods, you can add to the data structure instead ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required