Barnaba
Barnaba

Reputation: 677

watchr: Is it possible to do something when a file stopped changing?

Here's the description of the debounce function from Underscore.js:

Creates and returns a new debounced version of the passed function that will postpone its execution until after wait milliseconds have elapsed since the last time it was invoked. Useful for implementing behavior that should only happen after the input has stopped arriving. For example: rendering a preview of a Markdown comment, recalculating a layout after the window has stopped being resized, and so on.

Is there a simple way to implement such behavior using watchr? I'm editing database file, so I can't controll when it's saved. And I want to do something with ruby when I'm done editing.

Upvotes: 0

Views: 126

Answers (1)

Barnaba
Barnaba

Reputation: 677

Not so simple solution - with Thread:

class Debouncer                                         
  def initialize(seconds, &block)                       
    @seconds = seconds                                  
    @block = block                                      
  end                                                   

  def register_event                                    
    Thread.kill(@thread) unless @thread.nil?            
    @thread = Thread.new do                             
      sleep @seconds                         
      @block.call                                       
    end                                                 
  end                                                   

end                                                     

debouncer = Debouncer.new(30) { do_thing } 
watch( 'venus/database/(.*)' )   {|md| debouncer.register_event()}

Upvotes: 1

Related Questions