Skip to content

Instantly share code, notes, and snippets.

@sandro
Last active December 14, 2015 15:49
Show Gist options
  • Save sandro/5110419 to your computer and use it in GitHub Desktop.
Save sandro/5110419 to your computer and use it in GitHub Desktop.
require 'rb-fsevent'
unless ENV.has_key?('RSPEC_OPTIONS')
ENV['RSPEC_OPTIONS'] = '--fail-fast'
end
class Watcher
attr_accessor :now, :fsevent, :paths, :wip_enabled
REWRITE_REGEX = %r{(.*)(?:(app/)|(lib/))(.*)\.rb$}
def initialize
self.now = Time.now
self.fsevent = FSEvent.new
self.paths = Dir[File.expand_path("{app,spec,lib}")]
self.wip_enabled = false
end
def rspec_options
"#{ENV['RSPEC_OPTIONS']} #{wip_option}"
end
def start
set_up_fsevent
fsevent.run
end
def stop
fsevent.stop
end
def set_up_fsevent
fsevent.watch paths, no_defer: true do |directories|
puts "Detected change inside: #{directories.inspect}"
dir = directories.first[0...-1]
difference = (now - Time.now).to_i
files = `set -x && find #{dir} -type f -mtime #{difference}s`.split
self.now = Time.now
if files.any?
file = files.first.strip
if file !~ /_spec\.rb$/
file.sub! REWRITE_REGEX, '\1spec/\3\4_spec.rb'
end
if File.exists?(file) && File.extname(file) == '.rb'
system %(set -x && spring rspec #{rspec_options} #{file})
else
puts "File not executable: #{file}"
end
end
end
end
def toggle_wip!
self.wip_enabled = !wip_enabled
end
def wip_option
wip_enabled ? "-t wip" : ""
end
def wip_status
wip_enabled ? :enabled : :disabled
end
end
@watcher = Watcher.new
# Use Ctrl-\ to signal a QUIT event
trap('QUIT') do
@watcher.toggle_wip!
puts "\rWip tag #{@watcher.wip_status}..."
end
@watcher.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment