Autotest.add_hook :initialize do |at|
  
  at.libs = 'lib:spec'
  
  at.clear_mappings
  
  at.add_mapping(%r{^lib/will_paginate/(.+)\.rb$}) { |_, match|
    "spec/#{match[1]}_spec.rb"
  }
  at.add_mapping(%r{^spec/.+_spec\.rb$}) { |f, _| f }
  at.add_mapping(%r{^spec/(finders/activerecord_test_connector.rb|database.yml|fixtures/.+)$}) {
    'spec/finders/active_record_spec.rb'
  }
  at.add_mapping(%r{^spec/((spec_helper|shared/.+)\.rb|spec.opts)$}) {
    # simply re-run all specs
    at.files_matching %r{^spec/.+_spec\.rb$}
  }
  
  # add these to ignore list
  %w{ .git test/ rails/ Rakefile README.rdoc init.rb .autotest
      doc/ coverage/ LICENSE CHANGELOG .manifest will_paginate.gemspec examples/
      spec/tasks.rake spec/console spec/rcov.opts
    }.each { |path| at.add_exception path }
  
end

Autotest::Rspec.class_eval do
  # RSpec guys forgot about `libs` in make_test_cmd
  def make_test_cmd_with_libs(files_to_test)
    make_test_cmd_without_libs(files_to_test).sub(' -S ', " -S -I#{libs} ")
  end
  
  alias :make_test_cmd_without_libs :make_test_cmd
  alias :make_test_cmd :make_test_cmd_with_libs
  
  # ugh, we have to monkeypatch Autotest ...
  # the regexp it generates for the exception list just matches too much
  # 
  # SOLUTION: wrap it up in another regexp that anchors the whole expression to
  # the beginning of the path
  def exceptions
    unless defined? @exceptions then
      if @exception_list.empty? then
        @exceptions = nil
      else
        # old (BAD):
        # @exceptions = Regexp.union(*@exception_list)
        @exceptions = /^\.\/#{Regexp.union(*@exception_list)}/
      end
    end

    @exceptions
  end
end
