Recent ruby versions raise NameError: uninitialized constant Gem::Source when initializing a new Rails application by rails new, which could be fixed by updating the bundler gem.

Question

After installing a recent version of Ruby (namely v3.1.2), I encountered a NameError when initializing a Rails application by rails new.

The backtrace looks like:

.../bundler/rubygems_ext.rb:18:in `source': uninitialized constant Gem::Source (NameError)

      (defined?(@source) && @source) || Gem::Source::Installed.new
                                           ^^^^^^^^
Did you mean?  Gem::SourceList
        from .../bundler/rubygems_ext.rb:50:in `extension_dir'
        ...

Quick answer

Update the bundler gem using gem update bundler.

Full answer

Rubies recently published were shipped with bundler v2.3.7 which contains a known issue (rubygems/rubygems#5386) for autoloading Gem::Source.

Now since it has been reproduced and solved, an update of the bundler gem (up to v2.3.9 or newer version) could simply fix it.