module Rails::AppLoader

def exec_app

def exec_app
  original_cwd = Dir.pwd
  loop do
    if exe = find_executable
      contents = File.read(exe)
      if /(APP|ENGINE)_PATH/.match?(contents)
        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) && return if Pathname.new(Dir.pwd).root?
    # Otherwise keep moving upwards in search of an executable.
    Dir.chdir("..")
  end
end