TwitterSnowflake.rb
A Ruby library to handle Twitter snowflake IDs.
âŦī¸ Installation
There are two ways to install this library:
1. Bundler
Run bundle init
to generate a Gemfile, append the following line to it and run bundle install
.
gem 'twitter_snowflake', '~> 0.0.1'
2. Gem
Or you can use Ruby's package manager: gem. Open your terminal and run the following command:
gem install twitter_snowflake
đĻ Dependencies
Runtime
TwitterSnowflake.rb does not rely on any third-party library.
Development
đ Documentation
You can find the documentation in Rubydoc.
đšī¸ Usage
To parse a snowflake ID, use TwitterSnowflake.parse
:
require 'twitter_snowflake'
snowflake = TwitterSnowflake.parse 948_350_713_171_619_840
# => #<TwitterSnowflake::Snowflake:0x00005584b970d878
# @epoch=1288834974657,
# @id=948350713171619840,
# @increment=0,
# @process_id=19,
# @time=2018-01-02 22:30:04 -0200,
# @timestamp=1514939404181,
# @worker_id=0>
If you don't need a whole Snowflake
instance, you can use TwitterSnowflake
's utility class methods:
TwitterSnowflake. 948_350_713_171_619_840 # => 1514939404181
Calculations are made with Twitter's epoch by default (1_288_834_974_657
). You can change the epoch value by passing a keyword argument to TwitterSnowflake.parse
or TwitterSnowflake.timestamp
:
discord_epoch = 1_420_070_400_000
id = 649_027_890_029_133_824
TwitterSnowflake. id, epoch: discord_epoch # => 1574810707338
TwitterSnowflake.parse id, epoch: discord_epoch
# => <TwitterSnowflake::Snowflake:0x000056544c9e9818
# @epoch=1420070400000,
# @id=649027890029133824,
# @increment=0,
# @process_id=0,
# @time=2019-11-26 20:25:07 -0300,
# @timestamp=1574810707338,
# @worker_id=1>
It is also possible to generate a snowflake yourself with TwitterSnowflake.synthesize
:
snowflake = TwitterSnowflake.synthesize(
epoch: 1_420_070_400_000, # defaults to Twitter's epoch if no value is provided
timestamp: 1_574_810_707_338,
worker_id: 1,
process_id: 0,
increment: 0,
)
p snowflake.id # => 649027890029133824
đ License
TwitterSnowflake.rb is licensed under MIT.
âī¸ Contributors
- asyncnoodle â author & maintainer.
I'm looking to improve TwitterSnowflake.rb, so feel free to contribute!