Module: Ohm::Callbacks::Macros

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

Instance Method Summary collapse

Instance Method Details

#after(method, callback) ⇒ Array<callback>?

Use to add an after callback on ‘method`. Only symbols are allowed, no string eval, no block option also.

Examples:


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

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

protected
  def post_to_twitter!
    # do twitter posting here
  end

  def sync_ids
    # do something with the ids
  end
end

Parameters:

  • method (Symbol)

    the method type, ‘:validate`, `:create`, or `:save`

  • callback (Symbol)

    the name of the method to execute

Returns:

  • (Array<callback>, nil)

    the callback in an array or nil if the callback exists



102
103
104
# File 'lib/ohm/contrib/callbacks.rb', line 102

def after(method, callback)
  callbacks[:after][method] << callback
end

#before(method, callback) ⇒ Array<callback>?

Use to add a before callback on ‘method`. Only symbols are allowed, no string eval, no block option also.

Examples:


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

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

protected
  def timestamp!
    # do timestamping code here
  end

  def recalc_votes
    # do something here
  end
end

Parameters:

  • method (Symbol)

    the method type, ‘:validate`, `:create`, or `:save`

  • callback (Symbol)

    the name of the method to execute

Returns:

  • (Array<callback>, nil)

    the callback wrapped in an array or nil if the callback exists



71
72
73
74
75
# File 'lib/ohm/contrib/callbacks.rb', line 71

def before(method, callback)
  unless callbacks[:before][method].include? callback
    callbacks[:before][method] << callback
  end
end

#callbacksObject



107
108
109
# File 'lib/ohm/contrib/callbacks.rb', line 107

def callbacks
  @callbacks ||= Hash.new { |h, k| h[k] = Hash.new { |h, k| h[k] = [] }}
end