Created
January 4, 2023 17:13
-
-
Save brand-it/ced69998c2a06d9f0129787eb9fa8470 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SnowflakeId < ApplicationService | |
MAC_ADDRESS_PATTERN = /(?:(?:(?:[a-f0-9]{2}:){5})|(?:(?:[a-f0-9]{2}-){5}))[a-f0-9]{2}/i | |
MAC_ADDRESS = lambda { | |
address = RUBY_PLATFORM =~ /darwin/ ? `ifconfig` : `cat /sys/class/net/*/address` | |
address.match(MAC_ADDRESS_PATTERN).to_s.delete(':') | |
}.call | |
NODE_ID = -> { (MAC_ADDRESS.to_i(16) % 1023).to_s(2).rjust(10, '0') }.call | |
SEQUENCE_STARTED_AT = 1671750375309 | |
COUNTER_MAX = 4096 | |
def call | |
counter | |
['0', epoch_time, NODE_ID, counter].join.to_i(2) | |
end | |
private | |
def epoch_time | |
@epoch_time ||= (DateTime.current.strftime("%Q").to_i - SEQUENCE_STARTED_AT).to_s(2).rjust(41, '0') | |
end | |
def counter | |
if epoch_time != Thread.current[:last_epoch_time] | |
Thread.current[:last_epoch_time] = epoch_time | |
Thread.current[:snowflake_counter] = 0 | |
end | |
if Thread.current[:snowflake_counter].to_i >= COUNTER_MAX | |
@epoch_time = nil | |
return counter | |
end | |
@counter ||= (Thread.current[:snowflake_counter] += 1).to_s(2).rjust(12, '0') | |
end | |
end | |
def testing | |
integer = DateTime.current.strftime("%Q").to_i.to_s(2) | |
puts integer | |
time = integer | |
puts time | |
time = time.chars.each_slice(4).map(&:join).join(' ') | |
puts time | |
time = "%08b" % integer | |
puts time | |
time = time.chars.each_slice(4).map(&:join).join(' ') | |
puts time | |
time | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment