Skip to content

Commit

Permalink
1.8 compatibility for random_number method on SecureRandom.
Browse files Browse the repository at this point in the history
1.9 has its own version.
  • Loading branch information
NZKoz committed Oct 4, 2008
1 parent 923eb95 commit 1dfebd4
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 2 deletions.
4 changes: 2 additions & 2 deletions activesupport/lib/active_support/secure_random.rb
Expand Up @@ -164,13 +164,13 @@ def self.random_number(n=0)
hex = n.to_s(16)
hex = '0' + hex if (hex.length & 1) == 1
bin = [hex].pack("H*")
mask = bin[0].ord
mask = bin[0]
mask |= mask >> 1
mask |= mask >> 2
mask |= mask >> 4
begin
rnd = SecureRandom.random_bytes(bin.length)
rnd[0] = (rnd[0].ord & mask).chr
rnd[0] = rnd[0] & mask
end until rnd < bin
rnd.unpack("H*")[0].hex
else
Expand Down
4 changes: 4 additions & 0 deletions activesupport/test/secure_random_test.rb
Expand Up @@ -12,4 +12,8 @@ def test_hex
b2 = ActiveSupport::SecureRandom.hex(64)
assert_not_equal b1, b2
end

def test_random_number
assert ActiveSupport::SecureRandom.random_number(5000) < 5000
end
end

0 comments on commit 1dfebd4

Please sign in to comment.