Skip to content

Commit

Permalink
Conditionally check alphanumeric method parameters
Browse files Browse the repository at this point in the history
In ruby/securerandom#34, Random::Formatter was
removed from securerandom. This change broke the alphanumeric method
signature in Ruby 3.2 since the `chars` parameter isn't available
there yet.
  • Loading branch information
rafaelfranca committed Dec 2, 2024
1 parent 3726030 commit eff2f69
Showing 1 changed file with 24 additions and 4 deletions.
28 changes: 24 additions & 4 deletions activesupport/lib/active_support/core_ext/securerandom.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,18 @@ module SecureRandom
#
# p SecureRandom.base58 # => "4kUgL2pdQMSCQtjE"
# p SecureRandom.base58(24) # => "77TMHrHJFvFDwodq8w7Ev2m7"
def self.base58(n = 16)
alphanumeric(n, chars: BASE58_ALPHABET)
if SecureRandom.method(:alphanumeric).parameters.size == 2 # Remove check when Ruby 3.3 is the minimum supported version
def self.base58(n = 16)
alphanumeric(n, chars: BASE58_ALPHABET)
end
else
def self.base58(n = 16)
SecureRandom.random_bytes(n).unpack("C*").map do |byte|
idx = byte % 64
idx = SecureRandom.random_number(58) if idx >= 58
BASE58_ALPHABET[idx]
end.join
end
end

# SecureRandom.base36 generates a random base36 string in lowercase.
Expand All @@ -31,7 +41,17 @@ def self.base58(n = 16)
#
# p SecureRandom.base36 # => "4kugl2pdqmscqtje"
# p SecureRandom.base36(24) # => "77tmhrhjfvfdwodq8w7ev2m7"
def self.base36(n = 16)
alphanumeric(n, chars: BASE36_ALPHABET)
if SecureRandom.method(:alphanumeric).parameters.size == 2 # Remove check when Ruby 3.3 is the minimum supported version
def self.base36(n = 16)
alphanumeric(n, chars: BASE36_ALPHABET)
end
else
def self.base36(n = 16)
SecureRandom.random_bytes(n).unpack("C*").map do |byte|
idx = byte % 64
idx = SecureRandom.random_number(36) if idx >= 36
BASE36_ALPHABET[idx]
end.join
end
end
end

0 comments on commit eff2f69

Please sign in to comment.