Class: Rubyflake

Inherits:
Object
  • Object
show all
Defined in:
lib/rubyflake.rb

Constant Summary collapse

EPOCH =

01/01/2011

1293858000
FLAKE_TIMESTAMP_LENGTH =
41
FLAKE_RANDOM_LENGTH =
0b1111111111111111111111111
FLAKE_TIMESTAMP_SHIFT =
23

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(epoch = EPOCH) ⇒ Rubyflake

Returns a new instance of Rubyflake.



10
11
12
# File 'lib/rubyflake.rb', line 10

def initialize(epoch = EPOCH)
  @epoch = epoch
end

Class Method Details

.generate(epoch = Rubyflake::EPOCH) ⇒ Object



28
29
30
# File 'lib/rubyflake.rb', line 28

def generate(epoch = Rubyflake::EPOCH)
  Rubyflake.new(epoch).generate()
end

Instance Method Details

#generateObject



14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/rubyflake.rb', line 14

def generate
  # Figure out how many milliseconds have occurred since epoch.
  milliseconds = ((Time.now().to_f - @epoch) * 1000).to_i

  # Generate 23 random bits.
  random_bits = Random.new.rand(0..Rubyflake::FLAKE_RANDOM_LENGTH)

  # Shift our timestamp over 23 bits to make room for the random bits,
  # and then add the two together.
  (milliseconds << Rubyflake::FLAKE_TIMESTAMP_SHIFT) + random_bits.to_i

end