From 628671d18a5b17fb46371546c7298aa2d20255b7 Mon Sep 17 00:00:00 2001 From: John Bintz Date: Tue, 31 May 2011 16:15:19 -0400 Subject: [PATCH] force run feature --- README.md | 14 ++++++++------ lib/guard/rails.rb | 26 +++++++++++++++++++++++++- 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 0c0c74f..51d2e04 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,17 @@ -Want to restart your Rails dev server whilst you work? Now you can! +Want to restart your Rails development server whilst you work? Now you can! guard 'rails', :port => 5000 do watch('Gemfile.lock') watch(%r{^(config|lib)/.*}) end -Three fun options! +Four fun options! -* `:port` is the port number to run on (default 3000) -* `:environment` is the environment to use (default development) -* `:start_on_start` will start the server when starting Guard (default true) +* `:port` is the port number to run on (default `3000`) +* `:environment` is the environment to use (default `development`) +* `:start_on_start` will start the server when starting Guard (default `true`) +* `:force_run` kills any process that's holding open the listen port before attempting to (re)start Rails (default `false`). -This is super-alpha, but it works for me! +This is super-alpha, but it works for me! Only really hand-tested in Mac OS X. Feel free to fork'n'fix for other +OSes, and to add some real tests. diff --git a/lib/guard/rails.rb b/lib/guard/rails.rb index 4e9b543..3a55092 100644 --- a/lib/guard/rails.rb +++ b/lib/guard/rails.rb @@ -1,5 +1,6 @@ require 'guard' require 'guard/guard' +require 'rbconfig' module Guard class Rails < ::Guard::Guard @@ -7,7 +8,12 @@ module Guard def initialize(watchers = [], options = {}) super - @options = { :port => 3000, :environment => 'development', :start_on_start => true }.merge(options) + @options = { + :port => 3000, + :environment => 'development', + :start_on_start => true, + :force_run => false + }.merge(options) end def start @@ -36,6 +42,7 @@ module Guard end def start_rails + kill_unmanaged_pid! if options[:force_run] system %{sh -c 'cd #{Dir.pwd} && rails s -e #{options[:environment]} -p #{options[:port]} --pid #{pid_file} &'} while !File.file?(pid_file) sleep 0.5 @@ -48,6 +55,23 @@ module Guard system %{kill -INT #{File.read(pid_file).strip}} end end + + def unmanaged_pid + if RbConfig::CONFIG['host_os'] =~ /darwin/ + %x{lsof -P}.each_line { |line| + if line["*:#{options[:port]} "] + return line.split("\s")[1] + end + } + end + nil + end + + def kill_unmanaged_pid! + if pid = unmanaged_pid + system %{kill -INT #{pid}} + end + end end end