Class: Rails::Snowflake::Id::Callbacks

Inherits:
Object
  • Object
show all
Defined in:
lib/rails/snowflake/id.rb

Class Method Summary collapse

Class Method Details

.around_create(record) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/rails/snowflake/id.rb', line 11

def self.around_create(record)
  now = Time.now.utc

  if record.created_at.nil? || record.created_at >= now || record.created_at == record.updated_at || record.override_timestamps
    yield
  else
    record.id = Rails::Snowflake::Id.at(record.created_at)
    tries     = 0

    begin
      yield
    rescue ActiveRecord::RecordNotUnique
      raise if tries > 100

      tries     += 1
      record.id += rand(100)

      retry
    end
  end
end