0

I've watched a lot of Railscasts (thanks Ryan) and I need to recall some code I saw in one of them but my problem is I can't remember where to find it.

I can generate a 5 digit code using the code below and this is found in a method:

5.times.map { [*'A'..'Z'].sample }.join

but I need to be able to make sure that it's unique before saving. I remember Ryan using a loop of some sort in the model method to check that it is unique before saving.

Can you help?

tommyd456
  • 10,443
  • 26
  • 89
  • 163

2 Answers2

2

http://railscasts.com/episodes/274-remember-me-reset-password is the page you're looking for:

def generate_token(column)
  begin
    self[column] = SecureRandom.urlsafe_base64
  end while User.exists?(column => self[column])
end

So you could replace the SecureRandom.urlsafe_base64 part with your own code.

Dylan Markow
  • 123,080
  • 26
  • 284
  • 201
  • Good find! Really appreciate that - the code I want to create should only be 5 letters long and consist of capital letters only - is my method listed in the question the best way to do this do you know? – tommyd456 Oct 01 '13 at 18:33
  • @tommyd456 I'd normally recommend something like any of `SecureRandom`'s methods, but with your requirements your code should work just fine. There's a lengthy set of answers at http://stackoverflow.com/questions/88311/how-best-to-generate-a-random-string-in-ruby – Dylan Markow Oct 01 '13 at 19:55
1

first, replace your stuff with: SecureRandom.hex(5)

Then I get what you're looking for, something like this I bet:

value   = true
while value
  random = SecureRandom.hex(5)
  value  = Model.where(column: random).exists?
end
#here you have an unique `random`
apneadiving
  • 114,565
  • 26
  • 219
  • 213
  • I would like capital letters only so I don't think .hex will suit my needs (not that I mentioned this in my question) - or am I mistaken? – tommyd456 Oct 01 '13 at 18:34