Module: NoBacksies::CallbackMethods

Defined in:
lib/no_backsies.rb

Overview

The CallbackMethods module adds the callback methods which are used define and access callback definitions. Mixing-in this module is handled automatically, so you do not need to worry with it. In other words, consider the module private.

Instance Method Summary collapse

Instance Method Details

#callback(name, options = {}, &block) ⇒ Object

Define a callback.



85
86
87
# File 'lib/no_backsies.rb', line 85

def callback(name, options={}, &block)
  callbacks[name.to_sym] << [block, options]
end

#callback_express(express = {}, &block) ⇒ Object

Returns Hash of true/false activity state of callbacks.

TODO: Should expression be inherited?



102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/no_backsies.rb', line 102

def callback_express(express={}, &block)
  @_callback_express ||= Hash.new{|h,k| h[k]=true}

  if block
    tmp = @_callback_express.dup
    express.each{ |k,v| @_callback_express[k.to_sym] = !!v }
    block.call
    @_callback_express = tmp
  else
    express.each{ |k,v| @_callback_express[k.to_sym] = !!v }
  end

  @_callback_express
end

#callback_invoke(name, *args) ⇒ Object

Invoke a callback.



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/no_backsies.rb', line 118

def callback_invoke(name, *args)
  name = name.to_sym
  return unless callback_express[name]
  callbacks[name].each do |block, options|
    if options[:safe]
      callback_express(name=>false) do
        block.call(*args)            
      end
    else
      block.call(*args)
    end
    if options[:once]
      callbacks[name].delete([block, options])
    end
  end
end

#callbacksObject



90
91
92
93
94
95
96
97
# File 'lib/no_backsies.rb', line 90

def callbacks
  @_callbacks ||= (
    anc = ancestors[1..-1].find do |anc|
      anc.callbacks rescue nil  # TODO: Need faster way!
    end
    anc ? anc.callbacks.dup : Hash.new{|h,k| h[k]=[]}
  )
end