Created
June 23, 2014 00:26
-
-
Save kivanio/b7bd97d7cb65532187e1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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