Module | CouchRest::Callbacks |
In: |
lib/couchrest/mixins/callbacks.rb
|
Callbacks are hooks into the lifecycle of an object that allow you to trigger logic before or after an alteration of the object state.
Mixing in this module allows you to define callbacks in your class.
Example:
class Storage include ActiveSupport::Callbacks define_callbacks :save end class ConfigStorage < Storage save_callback :before, :saving_message def saving_message puts "saving..." end save_callback :after do |object| puts "saved" end def save _run_save_callbacks do puts "- save" end end end config = ConfigStorage.new config.save
Output:
saving... - save saved
Callbacks from parent classes are inherited.
Example:
class Storage include ActiveSupport::Callbacks define_callbacks :save save_callback :before, :prepare def prepare puts "preparing save" end end class ConfigStorage < Storage save_callback :before, :saving_message def saving_message puts "saving..." end save_callback :after do |object| puts "saved" end def save _run_save_callbacks do puts "- save" end end end config = ConfigStorage.new config.save
Output:
preparing save saving... - save saved
This method_missing is supplied to catch callbacks with keys and create the appropriate callback for future use.