Skip to content

Instantly share code, notes, and snippets.

@ackintosh
Created November 4, 2012 09:40
Show Gist options
  • Save ackintosh/4010931 to your computer and use it in GitHub Desktop.
Save ackintosh/4010931 to your computer and use it in GitHub Desktop.
Strategy Pattern and Proc Object in Ruby
class Report
attr_reader :title, :text
attr_accessor :formatter
def initialize(&formatter)
@title = 'report title'
@text = ['text1', 'text2', 'text3']
@formatter = formatter
end
def output_report
@formatter.call(self)
end
end
HTML_FORMATTER = lambda do |context|
puts "<html><head><title>#{context.title}</title></head>"
puts '<body>'
context.text.each do |line|
puts "<p>#{line}</p>"
end
puts '</body></html>'
end
report = Report.new(&HTML_FORMATTER)
report.output_report
# <html><head><title>report title</title></head>
# <body>
# <p>text1</p>
# <p>text2</p>
# <p>text3</p>
# </body></html>
PLAIN_FORMATTER = lambda do |context|
puts "*** #{report.title} ***"
report.text.each do |line|
puts(line)
end
end
report.formatter = PLAIN_FORMATTER
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