Module: ConcernsOnRails::Models::Hashable

Extended by:
ActiveSupport::Concern
Defined in:
lib/concerns_on_rails/models/hashable.rb

Constant Summary collapse

VALID_TYPES =
%i[hex uuid integer custom].freeze
MAX_GENERATION_ATTEMPTS =
10

Instance Method Summary collapse

Instance Method Details

#assign_hashable_valueObject

Assigns the generated value only when the field is blank, so callers can still pass an explicit value at create time.



83
84
85
86
87
88
89
90
91
92
# File 'lib/concerns_on_rails/models/hashable.rb', line 83

def assign_hashable_value
  field = self.class.hashable_field
  return if self[field].present?

  self[field] = if self.class.hashable_unique
                  unique_hashable_value(field)
                else
                  self.class.generate_hashable_value
                end
end

#unique_hashable_value(field) ⇒ Object

Best-effort uniqueness: retry on an in-Ruby collision before insert. Pair with a unique DB index for the real guarantee (mirrors Tokenizable).



96
97
98
99
100
101
102
103
# File 'lib/concerns_on_rails/models/hashable.rb', line 96

def unique_hashable_value(field)
  ConcernsOnRails::Models::Hashable::MAX_GENERATION_ATTEMPTS.times do
    candidate = self.class.generate_hashable_value
    return candidate unless self.class.unscoped.exists?(field => candidate)
  end
  raise "ConcernsOnRails::Models::Hashable: could not generate a unique value for '#{field}' " \
        "after #{ConcernsOnRails::Models::Hashable::MAX_GENERATION_ATTEMPTS} attempts"
end