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
-
#assign_hashable_value ⇒ Object
Assigns the generated value only when the field is blank, so callers can still pass an explicit value at create time.
-
#unique_hashable_value(field) ⇒ Object
Best-effort uniqueness: retry on an in-Ruby collision before insert.
Instance Method Details
#assign_hashable_value ⇒ Object
Assigns the generated value only when the field is blank, so callers can still pass an explicit value at create time.
103 104 105 106 107 108 109 110 111 112 |
# File 'lib/concerns_on_rails/models/hashable.rb', line 103 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).
116 117 118 119 120 121 122 123 |
# File 'lib/concerns_on_rails/models/hashable.rb', line 116 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 |