Module: Ohm::Callbacks

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

Overview

Minimalistic callback support for Ohm::Model.

You can implement callbacks by overriding any of the following methods:

   * before_validate
   * after_validate
   * before_create
   * after_create
   * before_save
   * after_save
   * before_update
   * after_update
   * before_delete
   * after_delete

If you prefer to do a class level declaration that is also possible.

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, Overrides

Instance Method Summary (collapse)

Instance Method Details

- (Object) create

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.



167
168
169
170
171
172
173
# File 'lib/ohm/contrib/callbacks.rb', line 167

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

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

- (Object) delete



196
197
198
199
200
201
202
# File 'lib/ohm/contrib/callbacks.rb', line 196

def delete
  execute_callback(:before, :delete)

  super.tap do |is_deleted|
    execute_callback(:after, :delete)  if is_deleted
  end
end

- (Object) save

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.



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/ohm/contrib/callbacks.rb', line 180

def save
  existing = !new?

  if valid?
    execute_callback(:before, :save)  
    execute_callback(:before, :update) if existing
  end

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

- (Object) validate

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.



156
157
158
159
160
# File 'lib/ohm/contrib/callbacks.rb', line 156

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