Skip to content

Instantly share code, notes, and snippets.

@rocknrollMarc
Forked from gnufied/debouncer.rb
Created March 10, 2014 07:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rocknrollMarc/9460633 to your computer and use it in GitHub Desktop.
Save rocknrollMarc/9460633 to your computer and use it in GitHub Desktop.
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