Skip to content

Commit 707104b

Browse files
authored
Merge pull request #9062 from baweaver/baweaver/platform-pattern-matching
Add pattern matching support to Gem::Platform
2 parents f778bf7 + 18f64c6 commit 707104b

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

lib/rubygems/platform.rb

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,37 @@ def to_s
146146
to_a.compact.join(@cpu.nil? ? "" : "-")
147147
end
148148

149+
##
150+
# Deconstructs the platform into an array for pattern matching.
151+
# Returns [cpu, os, version].
152+
#
153+
# Gem::Platform.new("x86_64-linux").deconstruct #=> ["x86_64", "linux", nil]
154+
#
155+
# This enables array pattern matching:
156+
#
157+
# case Gem::Platform.new("arm64-darwin-21")
158+
# in ["arm64", "darwin", version]
159+
# # version => "21"
160+
# end
161+
alias_method :deconstruct, :to_a
162+
163+
##
164+
# Deconstructs the platform into a hash for pattern matching.
165+
# Returns a hash with keys +:cpu+, +:os+, and +:version+.
166+
#
167+
# Gem::Platform.new("x86_64-darwin-20").deconstruct_keys(nil)
168+
# #=> { cpu: "x86_64", os: "darwin", version: "20" }
169+
#
170+
# This enables hash pattern matching:
171+
#
172+
# case Gem::Platform.new("x86_64-linux")
173+
# in cpu: "x86_64", os: "linux"
174+
# # Matches Linux on x86_64
175+
# end
176+
def deconstruct_keys(keys)
177+
{ cpu: @cpu, os: @os, version: @version }
178+
end
179+
149180
##
150181
# Is +other+ equal to this platform? Two platforms are equal if they have
151182
# the same CPU, OS and version.

test/rubygems/test_gem_platform.rb

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -683,4 +683,38 @@ def assert_local_match(name)
683683
def refute_local_match(name)
684684
refute_match Gem::Platform.local, name
685685
end
686+
687+
def test_deconstruct
688+
platform = Gem::Platform.new("x86_64-linux")
689+
assert_equal ["x86_64", "linux", nil], platform.deconstruct
690+
end
691+
692+
def test_deconstruct_keys
693+
platform = Gem::Platform.new("x86_64-darwin-20")
694+
assert_equal({ cpu: "x86_64", os: "darwin", version: "20" }, platform.deconstruct_keys(nil))
695+
end
696+
697+
def test_pattern_matching_array
698+
platform = Gem::Platform.new("arm64-darwin-21")
699+
result =
700+
case platform
701+
in ["arm64", "darwin", version]
702+
version
703+
else
704+
"no match"
705+
end
706+
assert_equal "21", result
707+
end
708+
709+
def test_pattern_matching_hash
710+
platform = Gem::Platform.new("x86_64-linux")
711+
result =
712+
case platform
713+
in cpu: "x86_64", os: "linux"
714+
"matched"
715+
else
716+
"no match"
717+
end
718+
assert_equal "matched", result
719+
end
686720
end

0 commit comments

Comments
 (0)