aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/core_ext/securerandom.rb
diff options
context:
space:
mode:
authorGuillermo Iguaran <guilleiguaran@gmail.com>2015-01-09 17:51:23 -0500
committerGuillermo Iguaran <guilleiguaran@gmail.com>2015-01-09 17:51:46 -0500
commitb1093977110f18ae0cafe56c3d99fc22a7d54d1b (patch)
tree08c688fd107285d218eae5256fffcdffdb3620b1 /activesupport/lib/active_support/core_ext/securerandom.rb
parent82dd93bd5eb6613c6fd8ba0725b30c273aba7008 (diff)
downloadrails-b1093977110f18ae0cafe56c3d99fc22a7d54d1b.tar.gz
rails-b1093977110f18ae0cafe56c3d99fc22a7d54d1b.tar.bz2
rails-b1093977110f18ae0cafe56c3d99fc22a7d54d1b.zip
Add SecureRandom.base58
Diffstat (limited to 'activesupport/lib/active_support/core_ext/securerandom.rb')
-rw-r--r--activesupport/lib/active_support/core_ext/securerandom.rb21
1 files changed, 21 insertions, 0 deletions
diff --git a/activesupport/lib/active_support/core_ext/securerandom.rb b/activesupport/lib/active_support/core_ext/securerandom.rb
new file mode 100644
index 0000000000..394cc76b98
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/securerandom.rb
@@ -0,0 +1,21 @@
+module SecureRandom
+ BASE58_ALPHABET = ('0'..'9').to_a + ('A'..'Z').to_a + ('a'..'z').to_a - ['0', 'O', 'I', 'l']
+ # SecureRandom.base58 generates a random base58 string.
+ #
+ # The argument _n_ specifies the length, of the random string to be generated.
+ #
+ # If _n_ is not specified or is nil, 16 is assumed. It may be larger in the future.
+ #
+ # The result may contain alphanumeric characters except 0, O, I and l
+ #
+ # p SecureRandom.base58 #=> "4kUgL2pdQMSCQtjE"
+ # p SecureRandom.base58(24) #=> "77TMHrHJFvFDwodq8w7Ev2m7"
+ #
+ 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