Skip to content

Instantly share code, notes, and snippets.

@kivanio
Created June 23, 2014 00:26
Show Gist options
  • Save kivanio/b7bd97d7cb65532187e1 to your computer and use it in GitHub Desktop.
Save kivanio/b7bd97d7cb65532187e1 to your computer and use it in GitHub Desktop.
module UniquelyIdentifiable
extend ActiveSupport::Concern
FINAL_BASE = 36
INTERMEDIATE_BASE = 16
SEPARATOR = 'a'
def generate_uid
real_id = self.id.to_s
rl = (6 - real_id.length) / 2
rl = 0 if rl < 0
"#{SecureRandom.hex(rl)}#{SEPARATOR}#{real_id}".to_i(INTERMEDIATE_BASE).to_s(FINAL_BASE)
end
def generate_and_store_uid
return nil unless persisted?
update_attribute(:uid, generate_uid) unless self.uid.present?
self.uid
end
module ClassMethods
def parse_uid uid
uid.to_i(FINAL_BASE).to_s(INTERMEDIATE_BASE).split(SEPARATOR).last.to_i
end
def find_with_uid uid
find_by_id parse_uid(uid)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment