Contexted Observers
I needed my Rails observers to have some context, and didn't want them to be aware of an entire controller or something equally jacked up. So here's something slightly less jacked up. At its basis, it provides a simple Context handler which has a stack of objects providing context. An example from the tests:
should "set the current context to be the last context hash" do
context, current_context = {:ashes => :ashes}, nil
ContextedObservers::Context.push_new(context) do
current_context = ContextedObservers::Context.current
end
assert_equal context, current_context
end
Current context becomes the hash => :ashes. Nesting another push_new
will add another context to the stack and make it current. When combined with ActionController / ActiveRecord::Observer, it allows for things such as:
class BlockContextController < ActionController::Base
before_filter :load_community
contextualize :except => :bar do
{:community => @community}
end
end
This provides a hash with the current community, in this example, as the current context. There's a shortcut method on ActiveRecord::Observer to access this context. This is because sometimes traversing the associations to get a piece of context isn't always possible / doesn't always make sense.