Skip to content

Commit

Permalink
add #timestamp to TypeID::UUID (#12)
Browse files Browse the repository at this point in the history
* add `#timestamp` to `TypeID::UUID`

* bump minor version
  • Loading branch information
broothie committed Jul 8, 2023
1 parent a06402c commit 44a5cbf
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 2 deletions.
2 changes: 1 addition & 1 deletion Gemfile.lock
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
PATH
remote: .
specs:
typeid (0.2.0)
typeid (0.2.1)
uuid7 (~> 0.2.0)

GEM
Expand Down
11 changes: 11 additions & 0 deletions lib/typeid/uuid.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,22 @@ def initialize(bytes)
super(string)
end

# Returns the +UUID+ encoded as a base32 +String+.
#
# @return [String]
def base32
TypeID::UUID::Base32.encode(bytes)
end

# Returns the timestamp of the +UUID+ as milliseconds since the Unix epoch.
#
# @return [Integer]
def timestamp
bytes[0..5]
.map.with_index { |byte, index| byte << (5 - index) * 8 }
.inject(:|)
end

# @return [String]
def inspect
"#<#{self.class.name} #{to_s}>"
Expand Down
2 changes: 1 addition & 1 deletion lib/typeid/version.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
class TypeID < String
VERSION = "0.2.0".freeze
VERSION = "0.2.1".freeze
end
6 changes: 6 additions & 0 deletions spec/lib/typeid/uuid_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,10 @@

it { is_expected.to eq base32 }
end

describe "#timestamp" do
subject(:timestamp) { uuid.timestamp }

it { is_expected.to eq 1686760803066 }
end
end

0 comments on commit 44a5cbf

Please sign in to comment.