Class: ULID::Rails::Type::Data

Inherits:
ActiveModel::Type::Binary::Data
  • Object
show all
Defined in:
lib/ulid/rails/type.rb

Direct Known Subclasses

PostgresqlType::Data, SqliteType::Data

Constant Summary collapse

INVALID_CHARACTERS_REGEX =
/[ilou]/i.freeze
VALID_INITIAL_CHARACTER_REGEX =
/^[0-7]/i.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value) ⇒ Data

Returns a new instance of Data.



64
65
66
67
# File 'lib/ulid/rails/type.rb', line 64

def initialize(value)
  @value = nil
  super if self.class.valid_ulid?(value)
end

Instance Attribute Details

#valueObject (readonly)

Returns the value of attribute value.



69
70
71
# File 'lib/ulid/rails/type.rb', line 69

def value
  @value
end

Class Method Details

.from_serialized(data) ⇒ Object



50
51
52
53
# File 'lib/ulid/rails/type.rb', line 50

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

.valid_ulid?(str) ⇒ Boolean

Returns:

  • (Boolean)


55
56
57
58
59
60
61
62
# File 'lib/ulid/rails/type.rb', line 55

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

  Base32::Crockford.valid?(str)
end

Instance Method Details

#hexObject

Raises:



71
72
73
74
75
76
77
78
# File 'lib/ulid/rails/type.rb', line 71

def hex
  return nil if @value.nil?

  hexed = Base32::Crockford.decode(@value).to_s(16).rjust(32, "0")
  raise ArgumentError if hexed.length > 32

  hexed
end