This post is part of a series of reviews on the book Design Patterns in Ruby. Check out the Introduction post for a full table of contents along with some generic principles regarding Design Patterns.

The template method’s main purpose is to basically organize different ways of running an algorithm.

Let’s say you have to generate reports and you need 2 ways of doing that, in plain text and in HTML. The thing is, both formats follow a certain step-by-step of how things should go, so you have this fixed step-by-step (or template) but a number of ways it could be implemented.

Transfering that diagram to our example, we’d have a generic Report class with a template method called generate_report(). This method would follow a certain algorithm such as header(), body() and footer(), which would have different implementations in each subclass of Report, in our case HTMLReport and PlainTextReport.

Translating all that to Ruby, we’d have:

class Report
	def initialize
		@title = 'My Report'	
	end

	def generate_report
		header
		body
		footer
	end

	def header
	end
	
	def body
	end

	def footer
	end
end

First our generic class with the template method defined.

class HTMLReport < Report
	def header
		puts "<html><body><h1>Header</h1>"
	end
	
	def body
		puts "<p>#{@title}</p>"
	end

	def footer
		puts "<div class='footer'>Footer</div></body></html>"
	end
end

class PlainTextReport < Report
	def header
		puts "Header\n\n"
	end
	
	def body
		puts "#{@title}\n\n"
	end

	def footer
		puts "Footer"
	end
end

And now the different implementations of the algorithm inside the template method generate_report(). Here’s some example code to see if the pattern really works:

html = HTMLReport.new
html.generate_report
#will output HTML

plain = PlainTextReport.new
plain.generate_report
#will output plain text

nothing = Report.new
nothing.generate_report
#will output nothing

Another alternative is to just raise exceptions on the header(), body() and footer() methods in the generic class so we’d be warned that we’re calling ‘abstract’ methods, but this way is simpler and cleaner.

Yes, template method is this simple, probably the simplest pattern of all. On to the next pattern, in the next post.