Skip to content

Commit

Permalink
feat: Gem::Requirement#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
req2 = req.dup
req2.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 0721762 commit 8e0c031
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
5 changes: 5 additions & 0 deletions lib/rubygems/requirement.rb
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,11 @@ def _sorted_requirements
def _tilde_requirements
@_tilde_requirements ||= _sorted_requirements.select {|r| r.first == "~>" }
end

def initialize_copy(other) # :nodoc:
@requirements = other.requirements.dup
super
end
end

class Gem::Version
Expand Down
8 changes: 8 additions & 0 deletions test/rubygems/test_gem_requirement.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@ def test_concat
assert_equal [[">=", v(1)], ["<", v(2)]], r.requirements
end

def test_initialize_copy
r = req("= 1.2")
r2 = r.dup

assert_equal r.requirements, r2.requirements
refute_same r.requirements, r2.requirements
end

def test_equals2
r = req "= 1.2"
assert_equal r, r.dup
Expand Down

0 comments on commit 8e0c031

Please sign in to comment.