Jump to content

The ultimate community for Ruby on Rails developers.


Photo

How to do a concurrent safe method?

thread synchronize concurrent

  • Please log in to reply
1 reply to this topic

#1 dlamet

dlamet

    Passenger

  • Members
  • 1 posts

Posted 12 March 2014 - 05:02 AM

I need to generate a safe customer facing identifier.  I have a method for pseudo-randomly generating a value for a new record.  I need to make sure that no two requests end up with the same value by happenstance.  Coming from the Java world I'm used to using synchronize on a method, but I'm finding that doesn't work.  Has it been removed?  How can I ensure that I end up with unique keys?

 

Thanks.



#2 Adam

Adam

    Inspector

  • Administrators
  • 78 posts

Posted 13 March 2014 - 09:28 PM   Best Answer

Assuming this is something you enter in the DB and you want something on a model, I'd go with something simple like this:

before_save do
  until self.identifier
    proposed_identifier = SecureRandom.uuid
    unless self.class.where(:identifier => proposed_identifier).exists?
      self.identifier = proposed_identifier
    end
  end
end


Adam Cooke

from aTech Media - UK-based Ruby on Rails developers. 

 

Follow me on Twitter  •  Check out my code on GitHub  •  Take a look at my designs





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users