diff --git a/lib/rails_ext/active_record_uuid_type.rb b/lib/rails_ext/active_record_uuid_type.rb index 02bdf3ed3..f2004f249 100644 --- a/lib/rails_ext/active_record_uuid_type.rb +++ b/lib/rails_ext/active_record_uuid_type.rb @@ -4,32 +4,34 @@ module ActiveRecord class Uuid < Binary BASE36_LENGTH = 25 # 36^25 > 2^128 - def self.generate - uuid = SecureRandom.uuid_v7 - hex = uuid.delete("-") - normalize_base36(hex.to_i(16)) - end + class << self + def generate + uuid = SecureRandom.uuid_v7 + hex = uuid.delete("-") + hex_to_base36(hex) + end - def self.normalize_base36(integer) - integer.to_s(36).rjust(BASE36_LENGTH, "0") + def hex_to_base36(hex) + hex.to_i(16).to_s(36).rjust(BASE36_LENGTH, "0") + end + + def base36_to_hex(base36) + base36.to_s.to_i(36).to_s(16).rjust(32, "0") + end end def serialize(value) return unless value - binary = hex(value).scan(/../).map(&:hex).pack("C*") + binary = Uuid.base36_to_hex(value).scan(/../).map(&:hex).pack("C*") super(binary) end - def hex(value) - value.to_s.to_i(36).to_s(16).rjust(32, "0") - end - def deserialize(value) return unless value hex = value.to_s.unpack1("H*") - Uuid.normalize_base36(hex.to_i(16)) + Uuid.hex_to_base36(hex) end def cast(value) diff --git a/test/test_helper.rb b/test/test_helper.rb index 12ab491ed..14893b030 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -154,8 +154,7 @@ module FixturesTestHelper # Format as UUID string and convert to base36 (25 chars) uuid = "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x" % bytes - hex = uuid.delete("-") - hex.to_i(16).to_s(36).rjust(25, "0") + ActiveRecord::Type::Uuid.hex_to_base36(uuid.delete("-")) end end end