Skip to content

Commit

Permalink
feat: Gem::Specification#initialize_copy deep-copies requirements
Browse files Browse the repository at this point in the history
to avoid accidentally mutating the original's state when doing:

```ruby
spec2 = spec.dup
spec2.required_rubygems_version.concat([">= 3.3.22"])
```

see rake-compiler/rake-compiler#236 for a
real-world use case that would be made simpler with this behavior.
  • Loading branch information
flavorjones committed Feb 2, 2024
1 parent 8e0c031 commit c1d5238
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
6 changes: 5 additions & 1 deletion lib/rubygems/specification.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2075,7 +2075,8 @@ def initialize(name = nil, version = nil)
end

##
# Duplicates array_attributes from +other_spec+ so state isn't shared.
# Duplicates Array and Gem::Requirement attributes from +other_spec+ so state isn't shared.
#

def initialize_copy(other_spec)
self.class.array_attributes.each do |name|
Expand All @@ -2097,6 +2098,9 @@ def initialize_copy(other_spec)
raise e
end
end

@required_ruby_version = other_spec.required_ruby_version.dup
@required_rubygems_version = other_spec.required_rubygems_version.dup
end

def base_dir
Expand Down
7 changes: 5 additions & 2 deletions test/rubygems/test_gem_specification.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1194,10 +1194,13 @@ def test_initialize_copy
assert_same spec.bindir, dup_spec.bindir

assert_equal ">= 0", spec.required_ruby_version.to_s
assert_same spec.required_ruby_version, dup_spec.required_ruby_version
assert_equal spec.required_ruby_version, dup_spec.required_ruby_version
refute_same spec.required_ruby_version, dup_spec.required_ruby_version

assert_equal ">= 0", spec.required_rubygems_version.to_s
assert_same spec.required_rubygems_version,
assert_equal spec.required_rubygems_version,
dup_spec.required_rubygems_version
refute_same spec.required_rubygems_version,
dup_spec.required_rubygems_version
end

Expand Down

0 comments on commit c1d5238

Please sign in to comment.