Skip to content

Commit

Permalink
Test and improve #valid_ulid? method
Browse files Browse the repository at this point in the history
Co-authored-by: Benjamin Quorning <[email protected]>
  • Loading branch information
vecerek and bquorning committed Dec 11, 2023
1 parent 26bce04 commit 01b7eaf
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/ulid/rails/type.rb
Original file line number Diff line number Diff line change
Expand Up @@ -44,15 +44,19 @@ def cast_string_to_ulid(value, data_class: Data)
end

class Data < ActiveModel::Type::Binary::Data
INVALID_CHARACTERS_REGEX = /[ilo]/i.freeze

def self.from_serialized(data)
deserialized = Base32::Crockford.encode(data.hex).rjust(26, "0")
new(deserialized)
end

def self.valid_ulid?(str)
return true if str.nil?
return false unless str.length == 26
return false if INVALID_CHARACTERS_REGEX.match?(str)

str.length == 26 && Base32::Crockford.valid?(str)
Base32::Crockford.valid?(str)
end

def initialize(value)
Expand Down
34 changes: 34 additions & 0 deletions test/ulid/rails/type_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
require "test_helper"

class ULID::Rails::Type::DataTest < Minitest::Test
def test_has_26_valid_characters
id = "01BX5ZZKBKACTAV9WEVGEMMVRZ"

assert ULID::Rails::Type::Data.valid_ulid?(id)
end

def test_length_less_than_26
id = "A" * 25

refute ULID::Rails::Type::Data.valid_ulid?(id)
end

def test_length_greater_than_26
id = "A" * 27

refute ULID::Rails::Type::Data.valid_ulid?(id)
end

# Crockford's Base32 is used as shown. This alphabet excludes
# the letters I, L, O, and U to avoid confusion and abuse.
# https://github.com/ulid/spec#encoding
def test_has_invalid_characters
invalid_characters = %w(I L O U)

invalid_characters.each do |char|
id = char * 26

refute ULID::Rails::Type::Data.valid_ulid?(id)
end
end
end

0 comments on commit 01b7eaf

Please sign in to comment.