Skip to content

Instantly share code, notes, and snippets.

@krisleech
Last active September 11, 2019 11:54
Show Gist options
  • Select an option

  • Save krisleech/2ca4e3cbc50c2b398549a1fba39bb323 to your computer and use it in GitHub Desktop.

Select an option

Save krisleech/2ca4e3cbc50c2b398549a1fba39bb323 to your computer and use it in GitHub Desktop.
inject messages to stdout for command

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
  end

We 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
  end

And 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment