Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions lib/rubygems/platform.rb
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,37 @@ def to_s
to_a.compact.join(@cpu.nil? ? "" : "-")
end

##
# Deconstructs the platform into an array for pattern matching.
# Returns [cpu, os, version].
#
# Gem::Platform.new("x86_64-linux").deconstruct #=> ["x86_64", "linux", nil]
#
# This enables array pattern matching:
#
# case Gem::Platform.new("arm64-darwin-21")
# in ["arm64", "darwin", version]
# # version => "21"
# end
alias_method :deconstruct, :to_a

##
# Deconstructs the platform into a hash for pattern matching.
# Returns a hash with keys +:cpu+, +:os+, and +:version+.
#
# Gem::Platform.new("x86_64-darwin-20").deconstruct_keys(nil)
# #=> { cpu: "x86_64", os: "darwin", version: "20" }
#
# This enables hash pattern matching:
#
# case Gem::Platform.new("x86_64-linux")
# in cpu: "x86_64", os: "linux"
# # Matches Linux on x86_64
# end
def deconstruct_keys(keys)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similar to #9060, could we add a few lines of documentation to provide a quick explanation.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added

{ cpu: @cpu, os: @os, version: @version }
end

##
# Is +other+ equal to this platform? Two platforms are equal if they have
# the same CPU, OS and version.
Expand Down
34 changes: 34 additions & 0 deletions test/rubygems/test_gem_platform.rb
Original file line number Diff line number Diff line change
Expand Up @@ -683,4 +683,38 @@ def assert_local_match(name)
def refute_local_match(name)
refute_match Gem::Platform.local, name
end

def test_deconstruct
platform = Gem::Platform.new("x86_64-linux")
assert_equal ["x86_64", "linux", nil], platform.deconstruct
end

def test_deconstruct_keys
platform = Gem::Platform.new("x86_64-darwin-20")
assert_equal({ cpu: "x86_64", os: "darwin", version: "20" }, platform.deconstruct_keys(nil))
end

def test_pattern_matching_array
platform = Gem::Platform.new("arm64-darwin-21")
result =
case platform
in ["arm64", "darwin", version]
version
else
"no match"
end
assert_equal "21", result
end

def test_pattern_matching_hash
platform = Gem::Platform.new("x86_64-linux")
result =
case platform
in cpu: "x86_64", os: "linux"
"matched"
else
"no match"
end
assert_equal "matched", result
end
end