Debug Output With Events
Lets say we have an object which performs a command:
class ReportAbnormalTempratures
def call
Temprature.greater_than(Tolerance.today).each do |temprature|
# do something...
end
end
As well as our application we might want to run this command from the console or a rake task. In the latter cases we might want to see some output or an ongoing progress report.
We could just add puts
statments but these clutter up the code and would show up when running the specs and if we are logging stdout would add a lot of noise.
What we could do is broadcast an event when something of interest happens and optionally, depending on the context, subscribe a listener to puts
to stdout.
class ReportAbnormalTempratures
include Wisper::Publisher
def call
Temprature.greater_than(Tolerance.today).each do |temprature|
broadcast(:match_found, temprature)
# do something...
end
end
And then in the console (or rake task):
command = ReportAbnormalTempratures.new
command.on(:match_found) { |temprature| puts "Match found: #{temprature}" }
command.call