Created
October 18, 2010 09:50
-
-
Save aalin/631985 to your computer and use it in GitHub Desktop.
Run a command when a file has been changed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env ruby | |
| # Usage: | |
| # runonupdate "spec spec/models/cat_spec.rb -O spec/spec.opts" app/models/cat.rb app/models/dog.rb | |
| # | |
| # This will run cat-specs whenever cat.rb or dog.rb is updated. | |
| class RunOnUpdate | |
| attr_reader :cmd | |
| attr_reader :files | |
| def initialize(cmd, files) | |
| raise "No command is given." if cmd.empty? | |
| raise "No files given." if files.empty? | |
| @cmd, @files = cmd, files | |
| @files_times = check_times | |
| end | |
| def run | |
| loop do | |
| system(cmd) if files_changed? | |
| sleep 1 | |
| end | |
| end | |
| protected | |
| def check_times | |
| files.inject({}) do |hash, filename| | |
| hash.merge(filename => File.stat(filename).mtime) | |
| end | |
| end | |
| def files_changed? | |
| new_times = check_times | |
| new_times.find do |filename, time| | |
| if time > @files_times[filename] | |
| puts "#{ filename } has been updated." | |
| @files_times = new_times | |
| end | |
| end | |
| end | |
| end | |
| cmd, *files = ARGV | |
| RunOnUpdate.new(cmd, files).run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment