Search code examples
rubyguard

Guard gem: run some code at startup or shutdown?


Is there a way to run some code at startup or shutdown of the Guard gem??

I'd like to execute some maintenance tasks automatically when starting or ending a development session.


Solution

  • Check out this: http://devblog.avdi.org/2011/06/15/a-guardfile-for-redis/

    Basically you can create an "Inline" Guard in your guardfile something like:

    require 'guard/compat/plugin'
    
    # the double-colons below are *required* for inline Guards!!!
    module ::Guard
      class MyPlugin < Plugin
        def start
          puts "Starting server"
        end
    
        # Called when `stop|quit|exit|s|q|e + enter` is pressed (when Guard quits).
        #
        # @raise [:task_has_failed] when stop has failed
        # @return [Object] the task result
        #
        def stop
          puts "Stopping server"
        end
    
        # Called when `reload|r|z + enter` is pressed.
        # This method should be mainly used for "reload" (really!) actions like reloading passenger/spork/bundler/...
        #
        # @raise [:task_has_failed] when reload has failed
        # @return [Object] the task result
        #
        def reload
          stop
          start
        end
      end
    end
    
    # Startup the inline plugin
    guard('my-plugin')
    
    
    ... other Guard config follows ...