Helpers for multiple publish/subscribe hooks using Rubys Observable.
Install manually:
gem install ruby-hooks Or add to Gemfile:
gem "ruby-hooks" and install with:
bundle install require"ruby-hooks"classTest1extendRubyHooks::InstanceHooksdefine_hook(:my_event_one)endtest=Test1.newtest.my_event_one# => RubyHooks::HookHook has all methods of Rubys Observable use it like this:
test.my_event_one.add_observer(object1)# changes will call object1.updatetest.my_event_one.add_observer(object2,:log)# changes will call object2.logtest.my_event_one.change# mark as changed, can be called multiple timestest.my_event_one.notify_observers(*args)# run the observers methods with given argstest.my_event_one.change_and_notify(*args)# mark as changed and run the observers methods with given argsruby-hooks comes with a support gem that allows to write yard docs for the hooks.
To automatically use the plugin add --plugin ruby-hooks to projects root directory .yardopts file.
Example documentation:
# called before executing command# @notify_param object [Object] the target that invoked the method# @notify_param stdout [String] standard output of the command, can be nil# @notify_param stderr [String] standard error output of the command, can be nildefine_hook:on_execute_dataAll hooks will be listed in Hooks section of the documentation, and the generated hook description will look roughly like this:
` - (Hook) on_execute_data` called before executing command **Returns:**- (`Hook`) — the Observable instance Hook#notify_observers block params: -**object** (`Object`) — the target that invoked the method -**stdout** (`String`) — standard output of the command, can be nil -**stderr** (`String`) — standard error output of the command, can be nilDefault notify_observers has no feedback in regard if the calls succeeded, it is very simple to extend Hook using:
moduleFindObserverdeffind_observer(*arg)result=nilifchanged?ifobserversresult=observers.finddo |k,v| k.sendv, *argendendchanged(false)endresultandresult.firstendendclassTest2extendRubyHooks::InstanceHooksdefine_hook(:my_event_two,:extends=>FindObserver)endTest2.new.my_event_two.find_observer(*args)this way users are not limited by the standard functionalities of Rubys Observable.
define_hook is just a small wrapper equivalent to:
require"ruby-hooks/hook"defmy_hook@my_hook ||= RubyHooks::Hook.new(:extends=>MyAwesomeModule)endIt's more code and less magic, to exclude ruby-hooks this should work:
require"observer"defmy_hook@my_hook ||= Object.new.tapdo |hook| hook.extendObservablehook.extendMyAwesomeModuleendendIt has certain limitation - all the hooks will be of class Object, it makes reading code and backtraces harder and you can not use the documentation helper with @notify_param.
This librarys is tested with ruby 1.9.2+, jruby and rbx.




