Created
November 11, 2013 11:30
-
-
Save gnufied/7411854 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module DeBouncer | |
def self.extened(base) | |
class << base | |
@deboucner_module = nil | |
end | |
end | |
def debounce(method_name, time) | |
if @debouncer_module | |
@debouncer_module.create_debouncer(method_name, time) | |
else | |
@debouncer_module = Module.new do | |
def self.create_debouncer(method_name, time) | |
define_method(method_name) do |*args, &block| | |
last_invoked_at = instance_variable_get(:"@#{method_name}_last_invoked_at") | |
if !last_invoked_at || (Time.now - last_invoked_at)*1000 > time | |
instance_variable_set(:"@#{method_name}_last_invoked_at", Time.now) | |
self.instance_variable_set(:"@#{method_name}_cached_result", | |
super(*args, &block) | |
) | |
else | |
instance_variable_get(:"@#{method_name}_cached_result") | |
end | |
end | |
end | |
end | |
@debouncer_module.create_debouncer(method_name, time) | |
prepend(@debouncer_module) | |
end | |
end | |
end | |
class Foo | |
extend DeBouncer | |
def initialize | |
@i = 0 | |
end | |
def hello | |
yield Time.now | |
end | |
def wow | |
puts "********** Calling wow #{Time.now}" | |
@i += 1 | |
end | |
debounce :hello, 4000 | |
debounce :wow, 4000 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment