From fbb36e36cc3080525b2b3fc0f0cd27d56c6d92bc Mon Sep 17 00:00:00 2001 From: Hiroshi SHIBATA Date: Mon, 16 Dec 2024 13:48:36 +0900 Subject: [PATCH 1/2] Restore SecureRandom.alphanumeric same as Random::Formatter.alphanumeric of Ruby 3.3/3.4 Fixes #35 --- lib/securerandom.rb | 10 ++++++++++ test/test_securerandom.rb | 6 ++++++ 2 files changed, 16 insertions(+) diff --git a/lib/securerandom.rb b/lib/securerandom.rb index db1fcaa..0bcd2b6 100644 --- a/lib/securerandom.rb +++ b/lib/securerandom.rb @@ -51,6 +51,16 @@ def bytes(n) return gen_random(n) end + # Compatibility methods for Ruby 3.2, we can remove this after dropping to support Ruby 3.2 + def alphanumeric(n = nil, chars: ALPHANUMERIC) + if RUBY_VERSION < '3.3' + n = 16 if n.nil? + choose(chars, n) + else + super n, chars: chars + end + end + private # :stopdoc: diff --git a/test/test_securerandom.rb b/test/test_securerandom.rb index 4c6bcf6..765fbc9 100644 --- a/test/test_securerandom.rb +++ b/test/test_securerandom.rb @@ -9,6 +9,12 @@ def setup @it = SecureRandom end + def test_alphanumeric_with_chars + assert_nothing_raised(ArgumentError) do + @it.alphanumeric(1, chars: ("0".."9").to_a) + end + end + # This test took 2 minutes on my machine. # And 65536 times loop could not be enough for forcing PID recycle. # TODO: We should run this test only on GitHub Actions. From 2c8cdfba7b52d342dd8de62476e9de4bea40fde9 Mon Sep 17 00:00:00 2001 From: Hiroshi SHIBATA Date: Mon, 16 Dec 2024 14:02:39 +0900 Subject: [PATCH 2/2] Only define compatible method in < Ruby 3.3 --- lib/securerandom.rb | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/lib/securerandom.rb b/lib/securerandom.rb index 0bcd2b6..442a711 100644 --- a/lib/securerandom.rb +++ b/lib/securerandom.rb @@ -53,13 +53,9 @@ def bytes(n) # Compatibility methods for Ruby 3.2, we can remove this after dropping to support Ruby 3.2 def alphanumeric(n = nil, chars: ALPHANUMERIC) - if RUBY_VERSION < '3.3' - n = 16 if n.nil? - choose(chars, n) - else - super n, chars: chars - end - end + n = 16 if n.nil? + choose(chars, n) + end if RUBY_VERSION < '3.3' private