Allow key pairs to be destructured

This commit is contained in:
Wilson Silva
2024-03-14 22:04:14 +00:00
parent 7c571d3b12
commit 838a2db834
3 changed files with 38 additions and 2 deletions

View File

@@ -38,8 +38,8 @@ module Nostr
# @param private_key [PrivateKey] 32-bytes hex-encoded private key.
# @param public_key [PublicKey] 32-bytes hex-encoded public key.
#
# @raise ArgumentError when the private key is not a +PrivateKey+
# @raise ArgumentError when the public key is not a +PublicKey+
# @raise ArgumentError when the private key is not a {PrivateKey}
# @raise ArgumentError when the public key is not a {PublicKey}
#
def initialize(private_key:, public_key:)
validate_keys(private_key, public_key)
@@ -48,6 +48,30 @@ module Nostr
@public_key = public_key
end
# Allows array destructuring of the KeyPair, enabling the extraction of +PrivateKey+ and +PublicKey+ separately
#
# @api public
#
# @example Implicit usage of `to_ary` for destructuring
# keypair = Nostr::KeyPair.new(
# private_key: Nostr::PrivateKey.new('7d1e4219a5e7d8342654c675085bfbdee143f0eb0f0921f5541ef1705a2b407d'),
# public_key: Nostr::PublicKey.new('15678d8fbc126fa326fac536acd5a6dcb5ef64b3d939abe31d6830cba6cd26d6'),
# )
# # The `to_ary` method can be implicitly used for array destructuring:
# private_key, public_key = keypair
# # Now `private_key` and `public_key` hold the respective values.
#
# @example Explicit usage of `to_ary`
# array_representation = keypair.to_ary
# # array_representation is now an array: [PrivateKey, PublicKey]
# # where PrivateKey and PublicKey are the respective objects.
#
# @return [Array<PrivateKey, PublicKey>] An array containing the {PrivateKey} and {PublicKey} in that order
#
def to_ary
[private_key, public_key]
end
private
# Validates the keys