Module: CouchRest::Callbacks

Included in:
ExtendedDocument
Defined in:
lib/couchrest/mixins/callbacks.rb

Overview

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

Defined Under Namespace

Modules: ClassMethods Classes: Callback, CallbackChain

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args, &blk) ⇒ Object

This method_missing is supplied to catch callbacks with keys and create the appropriate callback for future use.



312
313
314
315
316
317
# File 'lib/couchrest/mixins/callbacks.rb', line 312

def method_missing(meth, *args, &blk)
  if meth.to_s =~ /_run__([\w:]+)__(\w+)__(\w+)__callbacks/
    return self.class._create_and_run_keyed_callback($1, $2.to_sym, $3.to_sym, self, &blk)
  end
  super
end

Class Method Details

.included(klass) ⇒ Object



85
86
87
# File 'lib/couchrest/mixins/callbacks.rb', line 85

def self.included(klass)
  klass.extend ClassMethods
end

Instance Method Details

#run_callbacks(kind, options = {}, &blk) ⇒ Object



89
90
91
# File 'lib/couchrest/mixins/callbacks.rb', line 89

def run_callbacks(kind, options = {}, &blk)
  send("_run_#{kind}_callbacks", &blk)
end