module Rails::AppRailsLoader

def self.exec_app_rails

def self.exec_app_rails
  original_cwd = Dir.pwd
  loop do
    if exe = find_executable
      contents = File.read(exe)
      if contents =~ /(APP|ENGINE)_PATH/
        exec RUBY, exe, *ARGV
        break # non reachable, hack to be able to stub exec in the test suite
      elsif exe.end_with?('bin/rails') && contents.include?('This file was generated by Bundler')
        $stderr.puts(BUNDLER_WARNING)
        Object.const_set(:APP_PATH, File.expand_path('config/application', Dir.pwd))
        require File.expand_path('../boot', APP_PATH)
        require 'rails/commands'
        break
      end
    end
    # If we exhaust the search there is no executable, this could be a
    # call to generate a new application, so restore the original cwd.
    Dir.chdir(original_cwd) and return if Pathname.new(Dir.pwd).root?
    # Otherwise keep moving upwards in search of a executable.
    Dir.chdir('..')
  end
end

def self.find_executable

def self.find_executable
  EXECUTABLES.find { |exe| File.exist?(exe) }
end