Lets say we have some object which performs a command:
class ReportAbnormalTempratures
def self.call; new.call; end
def call
Temprature.greater_than(Tolerance.today).each do |temprature|
# do something...
end
endWe can run this command from out application, from a background process, a rake task, a cronjob etc.
But sometimes, e.g. when running from the console or a rake task, i.e. manually, we might want to see some output in realtime about what is happening.
We could just add puts statments but these clutter up the code and if we are logging out stdout may be overly verbose.
Instead we can 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 self.call; new.call; end
def call
Temprature.greater_than(Tolerance.today).each do |temprature|
broadcast(:match_found, temprature)
# do something...
end
endAnd in our rake task:
task report_abnormal_tempratures: :environment do
command = ReportAbnormalTempratures.new
command.on(:match_found) { |site| puts "Match found: #{temprature}" }
command.call
end