Working with Ruby
Occasional blog posts about Ruby updates, tools, editor tweaks, and random snippets. You might also be interested in my newer project that docuements lesser-known features in Ruby: Idiosyncratic Ruby.

Get your Microscope for MicroLogger: A small Logger on Top of MicroEvent.rb

Being impressed by MicroEvent.js I played with the thought to use such a library not only in JavaScript, but also in Ruby. The design pattern of this kind of message passing is called observer pattern and there is also a library in Ruby’s standard library and some more on rubygems.org. However, MicroEvent.js just nails it,

so I rebuilt it in Ruby: MicroEvent.rb – It is even shorter in Ruby, while having more features and more useful method return values than the JavaScript version. Ruby’s procs/blocks are the closest equivalent to JavaScript functions, which has the advantage that there is no need to use Ruby’s more complex methods.

Here you can see it in action, working under the hood of a simple logger library:

 1
2
3
4
5
6
7
8
9
10
11
12
class MicroLogger
  include MicroEvent

  def log(message, level = :info, extra = {}) 
    trigger level, message, {level: level, time: Time.now}.merge(extra)
  end 

  def register(level = :info, handler = nil, &block)
    bind level, &resolve_handler(handler || block)
  end 

  # ...

Which is used like this:

 1
2
3
4
5
6
7
8
9
$logger = MicroLogger.new
$logger.register :warn do |message, _|
   STDERR.puts message
end
$logger.register :warn do |message, meta|
  File.open("logfile.#{meta[:level]}.txt", "a"){ |f| f.puts "#{meta[:time]} | #{message}" }
end

$logger.log "hey", :warn # Will write to STDERR and logfile.warn.txt

You can find the full code on github. I am open for feedback on twitter.

Creative Commons License