Module: Identifiable::Model
- Extended by:
- ActiveSupport::Concern
- Defined in:
- lib/identifiable/model.rb
Instance Method Summary collapse
-
#set_public_id! ⇒ Object
If we don’t have a public ID yet, this method fetches the stylist for this class and finds a new, valid public id, and assigns it to the public ID column.
-
#to_key ⇒ Object
By overriding ActiveRecord’s ‘#to_key`, this means that Rails’ helpers, such as ‘dom_id` will use the public ID instead of the regular ID when identifying the record.
-
#to_param ⇒ Object
By overriding ActiveRecord’s ‘#to_param`, this means that Rails’ helpers, such as the ‘link_to` helpers will default to using the public ID instead of the regular ID when identifying the record.
Instance Method Details
#set_public_id! ⇒ Object
If we don’t have a public ID yet, this method fetches the stylist for this class and finds a new, valid public id, and assigns it to the public ID column.
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
# File 'lib/identifiable/model.rb', line 97 def set_public_id! # We don't want to set the public id if there's already a value in the # column, so exit early if that's the case. return unless self[self.class.identifiable_column].blank? # Create a new stylist for this record, that'll return random IDs # matching the class' style and length options. stylist = Identifiable::Stylist.new(record: self) new_public_id = nil # Loop until we find an unused public ID or we run out of attempts. 100.times do new_public_id = stylist.random_id break if self.class.find_by_public_id(new_public_id).nil? new_public_id = nil end # If we ran out of attempts, this probably means the length is too short, # since we kept colliding with existing records. Raise an error to let # the developers know that they need to up the length of the public ID. raise Identifiable::Errors::RanOutOfAttemptsToSetPublicIdError if new_public_id.nil? # If we got this far, we've got a new valid public ID, time to set it! self[self.class.identifiable_column] = new_public_id end |
#to_key ⇒ Object
By overriding ActiveRecord’s ‘#to_key`, this means that Rails’ helpers, such as ‘dom_id` will use the public ID instead of the regular ID when identifying the record.
127 128 129 |
# File 'lib/identifiable/model.rb', line 127 def to_key [self[self.class.identifiable_column]] end |
#to_param ⇒ Object
By overriding ActiveRecord’s ‘#to_param`, this means that Rails’ helpers, such as the ‘link_to` helpers will default to using the public ID instead of the regular ID when identifying the record.
134 135 136 |
# File 'lib/identifiable/model.rb', line 134 def to_param self[self.class.identifiable_column] end |