Skip to content

Instantly share code, notes, and snippets.

@manlycode
Forked from zdennis/report-exercise.rb
Created February 13, 2013 22:11
Show Gist options
  • Save manlycode/4948833 to your computer and use it in GitHub Desktop.
Save manlycode/4948833 to your computer and use it in GitHub Desktop.
0
#
# The goal of this exercise is work on identifying abstraction which helps simplify, document,
# and separate the concerns going on in file.
#
# Exercise:
# * Find related ideas in the below code
# * Abstract them out (methods, modules, classes, etc, you pick!)
# * If you find multiple ways, then do a separate gist for each way.
# * Rinse repeat until you see no other ways.
#
# Note: there is not enough of the code-base to run this code, so in order to run
# the code you'll have to implement the missing pieces.
class Report
def initialize(ship)
@title = "USS Enterprise Report"
logs = ship_logs_for_year(Time.now.year)
@text = log_lines(logs)
end
def ship_logs_for_year(year)
ship.logs.where(
"date >= '#{Time.now.year}-01-01' AND state=?",
"active"
).order("date DESC")
end
def log_lines(logs)
logs.map do |log|
status = "#{log.date}: #{log.message} (#{log.alert_level})"
end
end
def generate(format)
if format == :plain
output = []
output << "###### #{@title} ######"
@text.each_line do |line|
output << line
end
output.join "\n"
elsif format == :html
output = "<html>"
output << " <head>"
output << " <title>#{@title}</title>"
output << " </head>"
output << " <body>"
@text.each do |line|
output << " <p>#{line}</p>"
end
output << " </body>"
output << "</html>"
output
elsif format == :json
output = { title: @title, lines: [] }
@text.each do |line|
output[:lines] << line
end
output
else
raise "Unknown report format: #{format.inspect}"
end
end
end
class LogFormat
def for(sym)
puts self.inspect
self.const_get "#{self.to_s}::#{sym.to_s.capitalize}"
end
end
class LogFormat::Html < LogFormat
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment