max pleaner max pleaner - 3 months ago 12
Ruby Question

Cannot rerun my app with guard or rerun

So I have an app, the tree is something like this:

- Gemfile
- Guardfile
- source/
- dist/
- app.rb


The command to start the server is
ruby app.rb
( or
require_relative './app.rb'
, which does the same thing)

I want to run this command and re run it whenever any file changes.

The only exception is the dist/ folder - any file changes in there should be ignored.

Here's my attempt so far with
guard
and
guard-shell
(apologies for the code dump):

require 'childprocess'

# Global constant tracking whether the app has been started
RunningProcess = {gen_rb: false}

# Method to stop the app if it's been started
def ensure_exited_server
begin
RunningProcess[:gen_rb] && RunningProcess[:gen_rb].poll_for_exit(10)
rescue ChildProcess::TimeoutError
RunningProcess[:gen_rb].stop # tries increasingly harsher methods to kill the process.
end
nil
end

# Start the app using 'child-process'
def start_app
# prevent 'port in use' errors
ensure_exited_server
# The child-process gem starts a process and exposes its stdout
RunningProcess[:gen_rb] = ChildProcess.build("ruby", "gen.rb")
RunningProcess[:gen_rb].io.inherit!
RunningProcess[:gen_rb].start
nil
end

# Always start the app, not just when a file changes.
start_app

# The guard-shell gem runs a block whenever some set of files has changed.
guard :shell do
# This regex matches anything except the dist/ folder
watch /^[^dist\/].+/ do |m|
start_app
# Print a little message when a file changes.
m[0] + " has changed."
end
nil
end

# Make sure the app does not run after guard exits
at_exit { ensure_exited_server }


This doesn't ever restart my app.

The problem with rerun is something I raised an issue on their repo about: see https://github.com/alexch/rerun/issues/107

Answer

How about something like this for your Guardfile?

guard :shell do
  watch(%r{^source/.+\.(rb)}) do |m|
    `ruby app.rb`
  end

  watch('app.rb') do |m|
    `ruby app.rb`
  end
end

Instead of listing which directories to ignore, this watch states which directories/files to use.

Comments