Module: Ohm::Callbacks

Defined in:
lib/ohm/contrib/callbacks.rb

Overview

Minimalistic callback support for Ohm::Model.

Examples:


class Post < Ohm::Model
  include Ohm::Callbacks

  before :validate, :clean_decimals

  before :create, :timestamp!
  before :save,   :recalc_votes

  after  :create, :post_to_twitter!
  after  :save,   :sync_ids

protected
  def clean_decimals
    # sanitize the decimal values here
  end

  def timestamp!
    # do timestamping code here
  end

  def recalc_votes
    # do something here
  end

  def post_to_twitter!
    # do twitter posting here
  end

  def sync_ids
    # do something with the ids
  end
end

Defined Under Namespace

Modules: Macros

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



41
42
43
# File 'lib/ohm/contrib/callbacks.rb', line 41

def self.included(base)
  base.extend Macros
end

Instance Method Details

#createObject

The overriden create of Ohm::Model. It checks if the model is valid, and executes all before :create callbacks.

If the create succeeds, all after :create callbacks are executed.



137
138
139
140
141
142
143
# File 'lib/ohm/contrib/callbacks.rb', line 137

def create
  execute_callback(:before, :create)  if valid?

  super.tap do |is_created|
    execute_callback(:after, :create)  if is_created
  end
end

#saveObject

The overridden save of Ohm::Model. It checks if the model is valid, and executes all before :save callbacks.

If the save also succeeds, all after :save callbacks are executed.



150
151
152
153
154
155
156
# File 'lib/ohm/contrib/callbacks.rb', line 150

def save
  execute_callback(:before, :save)  if valid?

  super.tap do |is_saved|
    execute_callback(:after, :save)  if is_saved
  end
end

#validateObject

Overrides the validate method of Ohm::Model. This is a bit tricky, since typically you override this. Make sure you do something like:

def validate
  super

  # do your assertions
end

This ensures that you call this method when you defined your own validate method.

In all honesty, I don’t see the value of putting this here, and I’m still weighing if this is really needed.



126
127
128
129
130
# File 'lib/ohm/contrib/callbacks.rb', line 126

def validate
  execute_callback(:before, :validate)
  super
  execute_callback(:after, :validate)
end