Skip to content

Commit eff2f69

Browse files
committed
Conditionally check alphanumeric method parameters
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.
1 parent 3726030 commit eff2f69

File tree

1 file changed

+24
-4
lines changed

1 file changed

+24
-4
lines changed

activesupport/lib/active_support/core_ext/securerandom.rb

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,18 @@ module SecureRandom
1616
#
1717
# p SecureRandom.base58 # => "4kUgL2pdQMSCQtjE"
1818
# p SecureRandom.base58(24) # => "77TMHrHJFvFDwodq8w7Ev2m7"
19-
def self.base58(n = 16)
20-
alphanumeric(n, chars: BASE58_ALPHABET)
19+
if SecureRandom.method(:alphanumeric).parameters.size == 2 # Remove check when Ruby 3.3 is the minimum supported version
20+
def self.base58(n = 16)
21+
alphanumeric(n, chars: BASE58_ALPHABET)
22+
end
23+
else
24+
def self.base58(n = 16)
25+
SecureRandom.random_bytes(n).unpack("C*").map do |byte|
26+
idx = byte % 64
27+
idx = SecureRandom.random_number(58) if idx >= 58
28+
BASE58_ALPHABET[idx]
29+
end.join
30+
end
2131
end
2232

2333
# SecureRandom.base36 generates a random base36 string in lowercase.
@@ -31,7 +41,17 @@ def self.base58(n = 16)
3141
#
3242
# p SecureRandom.base36 # => "4kugl2pdqmscqtje"
3343
# p SecureRandom.base36(24) # => "77tmhrhjfvfdwodq8w7ev2m7"
34-
def self.base36(n = 16)
35-
alphanumeric(n, chars: BASE36_ALPHABET)
44+
if SecureRandom.method(:alphanumeric).parameters.size == 2 # Remove check when Ruby 3.3 is the minimum supported version
45+
def self.base36(n = 16)
46+
alphanumeric(n, chars: BASE36_ALPHABET)
47+
end
48+
else
49+
def self.base36(n = 16)
50+
SecureRandom.random_bytes(n).unpack("C*").map do |byte|
51+
idx = byte % 64
52+
idx = SecureRandom.random_number(36) if idx >= 36
53+
BASE36_ALPHABET[idx]
54+
end.join
55+
end
3656
end
3757
end

0 commit comments

Comments
 (0)