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_MAX =
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



34
35
36
# File 'lib/rubyflake.rb', line 34

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

.time(id, epoch = Rubyflake::EPOCH) ⇒ Object



38
39
40
# File 'lib/rubyflake.rb', line 38

def time(id, epoch = Rubyflake::EPOCH)
  Rubyflake.new(epoch).time(id)
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_MAX)

  # 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

#time(id) ⇒ Object

Extract the time from an ID.



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

def time(id)
  Time.at(((id >> Rubyflake::FLAKE_TIMESTAMP_SHIFT) + @epoch) / 1000)
end