Sha256: 8f8fc86c406da73f5d2cfa002e7facd6ef8e7cd0d7f3a0d105ab400331a56051

Contents?: true

Size: 1.39 KB

Versions: 5

Compression:

Stored size: 1.39 KB

Contents

require 'sys/uname'

module RSpactor
  class Listener
    EXTENSIONS = %w[rb erb builder haml yml]
    
    attr_reader :last_event, :callback, :pipe
    
    def initialize
      update_last_event
    end
    
    def watch(&block)
      @callback = block
    end
    
    def start
      @pipe = case Sys::Uname.sysname
      when 'Darwin'
        IO.popen("#{bin_path}/fsevent_watch .")
      when 'Linux'
        IO.popen("#{bin_path}/inotify_watch .")
      end
      
      watch_change
    end
    
    def stop
      Process.kill("HUP", pipe.pid) if pipe
    end
    
  private
    
    def watch_change
      while !pipe.eof?
        if line = pipe.readline
          modified_dirs = line.split(" ")
          files = modified_files(modified_dirs)
          update_last_event
          callback.call(files)
        end
      end
    end
    
    def modified_files(dirs)
      files = potentially_modified_files(dirs).select { |file| recent_file?(file) }
      files.map! { |file| file.gsub("#{Dir.pwd}/", '') }
    end
    
    def potentially_modified_files(dirs)
      Dir.glob(dirs.map { |dir| "#{dir}*.{#{EXTENSIONS.join(',')}}" })
    end
    
    def recent_file?(file)
      File.mtime(file) >= last_event
    end
    
    def update_last_event
      @last_event = Time.now
    end
    
    def bin_path
      File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'bin'))
    end
    
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
rspactor-0.7.0.beta.6 lib/rspactor/listener.rb
rspactor-0.7.0.beta.5 lib/rspactor/listener.rb
rspactor-0.7.0.beta.4 lib/rspactor/listener.rb
rspactor-0.7.0.beta.3 lib/rspactor/listener.rb
rspactor-0.7.0.beta.2 lib/rspactor/listener.rb