Skip to content

Commit f83e7a4

Browse files
committed
Add a conversion method for different formats
1 parent 77fba2a commit f83e7a4

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed

lib/ksuid.rb

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,28 @@ module KSUID
7575
# @return [String]
7676
MAX_STRING_ENCODED = 'aWgEPTl1tmebfsQzFP4bxwgy80V'
7777

78+
# Converts a KSUID-compatible value into an actual KSUID
79+
#
80+
# @api public
81+
#
82+
# @example Converts a base 62 KSUID string into a KSUID
83+
# KSUID.call('15Ew2nYeRDscBipuJicYjl970D1')
84+
#
85+
# @param ksuid [String, Array<Integer>, KSUID::Type] the KSUID-compatible value
86+
# @return [KSUID::Type] the converted KSUID
87+
# @raise [ArgumentError] if the value is not KSUID-compatible
88+
def self.call(ksuid)
89+
return unless ksuid
90+
91+
case ksuid
92+
when KSUID::Type then ksuid
93+
when Array then KSUID.from_bytes(ksuid)
94+
when String then cast_string(ksuid)
95+
else
96+
raise ArgumentError, "Cannot convert #{ksuid.inspect} to KSUID"
97+
end
98+
end
99+
78100
# The configuration for creating new KSUIDs
79101
#
80102
# @api private
@@ -167,4 +189,19 @@ def self.max
167189
def self.new(payload: nil, time: Time.now)
168190
Type.new(payload: payload, time: time)
169191
end
192+
193+
# Casts a string into a KSUID
194+
#
195+
# @api private
196+
#
197+
# @param ksuid [String] the string to convert into a KSUID
198+
# @return [KSUID::Type] the converted KSUID
199+
def self.cast_string(ksuid)
200+
if Base62.compatible?(ksuid)
201+
KSUID.from_base62(ksuid)
202+
else
203+
KSUID.from_bytes(ksuid)
204+
end
205+
end
206+
private_class_method :cast_string
170207
end

spec/ksuid_spec.rb

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,48 @@
1212

1313
expect(KSUID.config.random_generator).to eq(generator)
1414
end
15+
16+
describe '.call' do
17+
it 'returns KSUIDs in tact' do
18+
ksuid = KSUID.new
19+
20+
result = KSUID.call(ksuid)
21+
22+
expect(result).to eq(ksuid)
23+
end
24+
25+
it 'converts byte strings to KSUIDs' do
26+
ksuid = KSUID.new
27+
28+
result = KSUID.call(ksuid.to_bytes)
29+
30+
expect(result).to eq(ksuid)
31+
end
32+
33+
it 'converts byte arrays to KSUIDs' do
34+
ksuid = KSUID.new
35+
36+
result = KSUID.call(ksuid.__send__(:uid))
37+
38+
expect(result).to eq(ksuid)
39+
end
40+
41+
it 'converts base 62 strings to KSUIDs' do
42+
ksuid = KSUID.new
43+
44+
result = KSUID.call(ksuid.to_s)
45+
46+
expect(result).to eq(ksuid)
47+
end
48+
49+
it 'returns nil if passed nil' do
50+
result = KSUID.call(nil)
51+
52+
expect(result).to be_nil
53+
end
54+
55+
it 'raise an ArgumentError upon an unknown value' do
56+
expect { KSUID.call(1) }.to raise_error(ArgumentError)
57+
end
58+
end
1559
end

0 commit comments

Comments
 (0)