cache compiled callbacks

This commit is contained in:
Aaron Patterson 2013-05-10 11:00:25 -07:00
parent 3aee9126aa
commit ade7d365e4

@ -350,29 +350,46 @@ def initialize(name, config)
:scope => [ :kind ] :scope => [ :kind ]
}.merge!(config) }.merge!(config)
@chain = [] @chain = []
@callbacks = nil
end end
def each(&block); @chain.each(&block); end def each(&block); @chain.each(&block); end
def index(o); @chain.index(o); end def index(o); @chain.index(o); end
def insert(index, o); @chain.insert(index, o); end
def delete(o); @chain.delete(o); end
def clear; @chain.clear; self; end
def empty?; @chain.empty?; end def empty?; @chain.empty?; end
def insert(index, o)
@callbacks = nil
@chain.insert(index, o)
end
def delete(o)
@callbacks = nil
@chain.delete(o)
end
def clear
@callbacks = nil
@chain.clear
self
end
def initialize_copy(other) def initialize_copy(other)
@callbacks = nil
@chain = other.chain.dup @chain = other.chain.dup
end end
def compile def compile
callbacks = lambda { |env| return @callbacks if @callbacks
@callbacks = lambda { |env|
block = env.run_block block = env.run_block
env.value = !env.halted && (!block || block.call) env.value = !env.halted && (!block || block.call)
env env
} }
@chain.reverse_each do |callback| @chain.reverse_each do |callback|
callbacks = callback.apply(callbacks) @callbacks = callback.apply(@callbacks)
end end
callbacks @callbacks
end end
def append(*callbacks) def append(*callbacks)
@ -389,16 +406,19 @@ def chain; @chain; end
private private
def append_one(callback) def append_one(callback)
@callbacks = nil
remove_duplicates(callback) remove_duplicates(callback)
@chain.push(callback) @chain.push(callback)
end end
def prepend_one(callback) def prepend_one(callback)
@callbacks = nil
remove_duplicates(callback) remove_duplicates(callback)
@chain.unshift(callback) @chain.unshift(callback)
end end
def remove_duplicates(callback) def remove_duplicates(callback)
@callbacks = nil
@chain.delete_if { |c| callback.duplicates?(c) } @chain.delete_if { |c| callback.duplicates?(c) }
end end