exsnake
exsnake

Reputation: 1823

obfuscate id in Rails with begin range

I'm trying to obfuscate the ids in several models.

I accomplish this using the solution proposed in this GitHub issue and is working fine (I don't want to use a gem due the future compatibility problems).

The problem is that ids generated are small. I want them to start over the 1000000. How can accomplish this in a correct way?

The code for the model:

 before_create :generate_random_id

 private 

 def generate_random_id
   self.id = SecureRandom.uuid
 end 

Upvotes: 0

Views: 248

Answers (2)

PressingOnAlways
PressingOnAlways

Reputation: 12356

The reason why the id is small is because the UUID string is being converted into an integer. Use SecureRandom.random_number(100000000000) instead.

You need to check if the number is bigger than 1000000 and not already in the system.

before_create :generate_random_id

private 

def generate_random_id
  while self.id.nil? || Model.find_by_id(self.id) do
    self.id = SecureRandom.random_number(100000000000) + 1000000
  end
end 

OR

Use uuid as the native id. Postgresql supports this natively pretty well with an extension:

CREATE EXTENSION pgcrypto;  
CREATE TABLE mymodel(  
   id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
   ...
);

Upvotes: 1

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

I want them to start over the 1000000. How can accomplish this in a correct way?

So just shift the starting point.

def generate_random_id
  self.id = 1_000_000 + rand(1_000_000_000)
  # then, of course, make sure that you don't have a collision
  # (an existing record with this random id)
end 

Upvotes: 0

Related Questions