def retrying_on_collision(retry_count=0)
      yield
    rescue ActiveRecord::RecordNotUnique
      raise TooManyCollisionsException.new('Too many db uniqueness collisions') if retry_count >= max_collision_retries
      rand_range = wait_time_seconds[retry_count]
      sleep(rand(rand_range.end - rand_range.begin) + rand_range.begin) # rand(range) seems broken in 1.9.2-p320, so work around
      retrying_on_collision(retry_count + 1) { yield }
    end
def retrying_on_collision(retry_count=0)
      yield
    rescue ActiveRecord::RecordNotUnique
      raise TooManyCollisionsException.new('Too many db uniqueness collisions') if retry_count >= max_collision_retries
      rand_range = wait_time_seconds[retry_count]
      sleep(rand(rand_range.end - rand_range.begin) + rand_range.begin) # rand(range) seems broken in 1.9.2-p320, so work around
      retrying_on_collision(retry_count + 1) { yield }
    end
usage like this:

 extend IndexedSearch::Collision
 def find_or_create_foos_ids(foos)
   retrying_on_collision do
     ids_hash = quick_find_current_foos_ids(foos)
     foos.collect { |foo| ids_hash[foo] || expensive_create_foo_and_return_id(foo) }
   end
 end

 or something else similar... :)