Skip to content

Instantly share code, notes, and snippets.

@ackintosh
Created October 24, 2012 11:36
Show Gist options
  • Save ackintosh/3945597 to your computer and use it in GitHub Desktop.
Save ackintosh/3945597 to your computer and use it in GitHub Desktop.
Template Method Pattern in Ruby
class Report
def initialize
@title = 'report title'
@text = ['text1', 'text2', 'text3']
end
def output_report
output_start
output_body
output_end
end
def output_start
end
def output_body
@text.each do |line|
output_line(line)
end
end
def output_line(line)
raise 'Called abstract method !!'
end
def output_end
end
end
class HTMLReport < Report
def output_start
puts "<html><head><title>#{@title}</title></head><body>"
end
def output_line(line)
puts "<p>#{line}</p>"
end
def output_end
puts '</body></html>'
end
end
class PlainTextReport < Report
def output_start
puts "*** #{@title} ***"
end
def output_line(line)
puts line
end
end
html_report = HTMLReport.new
html_report.output_report
# <html><head><title>report title</title></head><body>
# <p>text1</p>
# <p>text2</p>
# <p>text3</p>
# </body></html>
plain_report = PlainTextReport.new
plain_report.output_report
# *** report title ***
# text1
# text2
# text3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment