Module: Philiprehberger::Debounce::Mixin::ClassMethods
- Defined in:
- lib/philiprehberger/debounce/mixin.rb
Overview
Class-level macros for debouncing and throttling methods.
Instance Method Summary collapse
-
#debounce_method(method_name, wait:, leading: false, trailing: true) ⇒ void
Wraps an instance method so that calls are debounced.
-
#throttle_method(method_name, interval:, leading: true, trailing: false) ⇒ void
Wraps an instance method so that calls are throttled.
Instance Method Details
#debounce_method(method_name, wait:, leading: false, trailing: true) ⇒ void
This method returns an undefined value.
Wraps an instance method so that calls are debounced.
The original method is renamed and a new method is created that delegates to a Debouncer instance stored on the object.
38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/philiprehberger/debounce/mixin.rb', line 38 def debounce_method(method_name, wait:, leading: false, trailing: true) original = :"_undebounced_#{method_name}" alias_method original, method_name define_method(method_name) do |*args| @_debouncers ||= {} @_debouncers[method_name] ||= Debouncer.new( wait: wait, leading: leading, trailing: trailing ) { |*a| send(original, *a) } @_debouncers[method_name].call(*args) end end |
#throttle_method(method_name, interval:, leading: true, trailing: false) ⇒ void
This method returns an undefined value.
Wraps an instance method so that calls are throttled.
The original method is renamed and a new method is created that delegates to a Throttler instance stored on the object.
62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/philiprehberger/debounce/mixin.rb', line 62 def throttle_method(method_name, interval:, leading: true, trailing: false) original = :"_unthrottled_#{method_name}" alias_method original, method_name define_method(method_name) do |*args| @_throttlers ||= {} @_throttlers[method_name] ||= Throttler.new( interval: interval, leading: leading, trailing: trailing ) { |*a| send(original, *a) } @_throttlers[method_name].call(*args) end end |