Skip to content

Commit

Permalink
Add a conversion method for different formats
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelherold committed May 29, 2018
1 parent 77fba2a commit f83e7a4
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
37 changes: 37 additions & 0 deletions lib/ksuid.rb
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,28 @@ module KSUID
# @return [String]
MAX_STRING_ENCODED = 'aWgEPTl1tmebfsQzFP4bxwgy80V'

# Converts a KSUID-compatible value into an actual KSUID
#
# @api public
#
# @example Converts a base 62 KSUID string into a KSUID
# KSUID.call('15Ew2nYeRDscBipuJicYjl970D1')
#
# @param ksuid [String, Array<Integer>, KSUID::Type] the KSUID-compatible value
# @return [KSUID::Type] the converted KSUID
# @raise [ArgumentError] if the value is not KSUID-compatible
def self.call(ksuid)
return unless ksuid

case ksuid
when KSUID::Type then ksuid
when Array then KSUID.from_bytes(ksuid)
when String then cast_string(ksuid)
else
raise ArgumentError, "Cannot convert #{ksuid.inspect} to KSUID"
end
end

# The configuration for creating new KSUIDs
#
# @api private
Expand Down Expand Up @@ -167,4 +189,19 @@ def self.max
def self.new(payload: nil, time: Time.now)
Type.new(payload: payload, time: time)
end

# Casts a string into a KSUID
#
# @api private
#
# @param ksuid [String] the string to convert into a KSUID
# @return [KSUID::Type] the converted KSUID
def self.cast_string(ksuid)
if Base62.compatible?(ksuid)
KSUID.from_base62(ksuid)
else
KSUID.from_bytes(ksuid)
end
end
private_class_method :cast_string
end
44 changes: 44 additions & 0 deletions spec/ksuid_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,48 @@

expect(KSUID.config.random_generator).to eq(generator)
end

describe '.call' do
it 'returns KSUIDs in tact' do
ksuid = KSUID.new

result = KSUID.call(ksuid)

expect(result).to eq(ksuid)
end

it 'converts byte strings to KSUIDs' do
ksuid = KSUID.new

result = KSUID.call(ksuid.to_bytes)

expect(result).to eq(ksuid)
end

it 'converts byte arrays to KSUIDs' do
ksuid = KSUID.new

result = KSUID.call(ksuid.__send__(:uid))

expect(result).to eq(ksuid)
end

it 'converts base 62 strings to KSUIDs' do
ksuid = KSUID.new

result = KSUID.call(ksuid.to_s)

expect(result).to eq(ksuid)
end

it 'returns nil if passed nil' do
result = KSUID.call(nil)

expect(result).to be_nil
end

it 'raise an ArgumentError upon an unknown value' do
expect { KSUID.call(1) }.to raise_error(ArgumentError)
end
end
end

0 comments on commit f83e7a4

Please sign in to comment.