Ruby is a nice little language, but I think it wouldn’t have exploded in popularity like it did without Rails. Nowadays, Ruby still seems to be the first choice of early-stage startups. A big part of that is how easy ActiveRecord makes database access.

Adrian was doing some code reviews, when he came across this line:

  generate_ident_value(ident, value.to_s + rand(10).to_s)

“Um… what’s this doing?”

Well, they needed to generate unique identifiers based on a user’s name, so joebob becomes joebob1, and the next joebob becomes joebob2 and so on. “We were having a problem with duplicates- if a user was deleted, we were accidentally re-using their ID, so I added the call to rand to fix that.”

Adrian took a look at the surrounding method’s previous version.

 def generate_ident_value(ident, value = 1)
    if query.find_by(ident: ident + value.to_s)
      generate_ident_value(ident, value + 1) # this is the line which changed
      ident + value.to_s

Yes- this method attempts to see if joebob1 already exists in the database, and if it does, tries again with joebob2, with a nice recursive call. Changing value + 1 to value.to_s + rand(10).to_s meant, instead of trying joebob2, theyd instead tryjoebob15, thenjoebob159, thenjoebob1597`, for example.

Adrian pointed out this was an insane solution. “You’re right, we should just keep every generated ident in a database table.”

“That’s not…”

“And when we combine it with the random ident I added, it’ll be super unique, and we won’t have to worry about deletions!”

“No, that’s…”

That’s exactly what ended up happening, despite Adrian’s protests. Because of the random approach of tacking characters on the end, the field size had to increase to 20 characters, then 30. Adrian expects it to go up to 40 before year’s end. He’s not planning to be around to see that though- he’s already made plans to move onto another position.

[Advertisement] Otter - Provision your servers automatically without ever needing to log-in to a command prompt. Get started today!