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.



121
122
123
# File 'lib/no_backsies.rb', line 121

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?



138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/no_backsies.rb', line 138

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, &superblock) ⇒ Object

Invoke a callback.



155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/no_backsies.rb', line 155

def callback_invoke(name, *args, &superblock)
  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, &superblock)            
      end
    else
      block.call(*args, &superblock)
    end
    if options[:once]
      callbacks[name].delete([block, options])
    end
    if !options[:superless]
      superblock.call if superblock
    end
  end
end

#callbacksObject



126
127
128
129
130
131
132
133
# File 'lib/no_backsies.rb', line 126

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