Sentinel

Transparent (unobtrusive) Observers for your Rubies.

Why?

Developed for an specific need we had at Busk, Sentinel is a very small library that provides a way to add what we call “Transparent Observers” to your Ruby code. This means that you do not need to modify the observed methods (following the most common implementation of Observers), just use a mixin and declare your observers.

How?

First, install the gem:


$ [sudo] gem install sentinel

Then, add it as a dependency in your code using your favorite way (a simple require or mechanisms like the Bundler gem).

To use it, first you’ll need an observer class with the Sentinel mixin. This class contains the methods to be notified and the configuration specifying what subject methods will be observed. See an example below:


class MyObserver
  include Sentinel

  observe MyClass, :instance_method
  observe MyClass, :class_method, :method_to_notify => :notify_class_method, :class_method => true #to observe a class method

  def self.notify(options, *args)
    puts "Do your thing!"
  end

  def self.notify_class_method(options, *args)
    puts "Called class_method!"
  end
end

As you can see, Sentinel can observe both class and instance methods. The notify method is the default one if you don’t specify the :method_to_notify option. Now, our actual class:


class MyClass
  def instance_method
    puts "Hi from the instance method!"
  end

  def self.class_method
    puts "Hi from the class method!"
  end
end

And… that’s it! Every time the subject (in this case, MyClass) method is called, the specified observer method will be called before it, then it will run normally. The parameters passed to the subject method are passed to the observer method via the *args array. The options hash contains the key :subject, which contains the actual subject object in case you want to use it, like below:


class MyObserver
  include Sentinel

  observe MyClass, :instance_method

  def self.notify(options, *args)
    puts "Called from #{options[:subject]} with arguments #{args.inspect}"
  end
end

Note on Patches/Pull Requests

  • Fork the project.
  • Make your feature addition or bug fix.
  • Add tests for it. This is important so I don’t break it in a future version unintentionally.
  • Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
  • Send me a pull request. Bonus points for topic branches.

Copyright

Copyright © 2010 Lucas HĂșngaro. See LICENSE for details.