Bug #16257
Updated by tonci (Tonči Damjanić) about 5 years ago
Instantiating `Gem::Version` objects via `new` actually returns singletons, which is not obvious nor is this documented anywhere:
~~~
irb(main):001:0> v1 = Gem::Version.new("2.2.0")
=> #<Gem::Version "2.2.0">
irb(main):002:0> v1.frozen?
=> false
irb(main):003:0> v2 = Gem::Version.new("2.2.0")
=> #<Gem::Version "2.2.0">
irb(main):004:0> v2.frozen?
=> false
irb(main):005:0> v1.freeze
=> #<Gem::Version "2.2.0">
irb(main):006:0> v1.frozen?
=> true
irb(main):007:0> v2.frozen?
=> true
irb(main):008:0> v1.object_id == v2.object_id
=> true
~~~
Affected Ruby versions:
* `ruby 2.6.5p114 (2019-10-01 revision 67812) [x86_64-linux]`
* `ruby 2.4.4p296 (2018-03-28 revision 63013) [x86_64-darwin17]`
This feature can cause side-effects if the application freezes a `Gem::Version` that matches the version of one of the loaded gems.
```
class ApplicationController < ActionController::Base
...
SOME_VERSION = Gem::Version.new('2.2.0').freeze
end
```
Error raised during `rails console` startup (notice that `js_cookie_rails` is on the same version):
```
Invalid gemspec in [/var/www/application-server/vendor/bundle/ruby/2.4/specifications/js_cookie_rails-2.2.0.gemspec]: can't modify frozen Gem::Version
/usr/local/share/ruby/gems/2.4/gems/bundler-2.0.2/lib/bundler/stub_specification.rb:97:in `_remote_specification': The gemspec for js_cookie_rails-2.2.0 at /var/www/application-server/vendor/bundle/ruby/2.4/specifications/js_cookie_rails-2.2.0.gemspec was missing or broken. Try running `gem pristine js_cookie_rails -v 2.2.0` to fix the cached spec. (Bundler::GemspecError)
from /usr/local/share/ruby/gems/2.4/gems/bundler-2.0.2/lib/bundler/remote_specification.rb:106:in `method_missing'
from /usr/share/ruby/vendor_ruby/2.4/rubygems/specification.rb:1040:in `block in find_by_path'
from /usr/local/share/ruby/gems/2.4/gems/bundler-2.0.2/lib/bundler/spec_set.rb:148:in `each'
from /usr/local/share/ruby/gems/2.4/gems/bundler-2.0.2/lib/bundler/spec_set.rb:148:in `each'
from /usr/share/ruby/vendor_ruby/2.4/rubygems/specification.rb:1039:in `find'
from /usr/share/ruby/vendor_ruby/2.4/rubygems/specification.rb:1039:in `find_by_path'
from /usr/share/ruby/vendor_ruby/2.4/rubygems.rb:209:in `try_activate'
...
```
Unfreezing the `SOME_VERSION` constant fixes the gemspec error.