Created
April 18, 2011 14:35
-
-
Save ianterrell/925464 to your computer and use it in GitHub Desktop.
Quickly generate pretty referral codes through Base-N encoding
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
# Want to give your users nice referral URLs, like http://www.service.com/?r=2ab3 ? | |
# | |
# A fast and easy 1-1 method is to use base-n encoded numbers. | |
# | |
# For instance, encode the user's id in base 36. In Ruby, this is easy: | |
# > 272927.to_s(36) | |
# => "5ulb" | |
# | |
# To get the base 10 id back again is just as easy: | |
# > "5ulb".to_i(36) | |
# => 272927 | |
# | |
# What if you have a new service and your user ids start with 1, 2, 3, and you don't want that? | |
# One solution is to add something to the id or multiply it by something, or both. | |
# | |
# Here's something you can dump in your user model: | |
### | |
## Sharing | |
# | |
# If you change these constants, existing values will not be accurate | |
SHARING_ID_ADDITION = 1693 | |
SHARING_ID_MULTIPLIER = 7 | |
SHARING_ID_BASE = 36 | |
def sharing_id | |
self.class.to_sharing_id(id) | |
end | |
class << self | |
def to_sharing_id(decimal_id) | |
((decimal_id + SHARING_ID_ADDITION)*SHARING_ID_MULTIPLIER).to_s(SHARING_ID_BASE) | |
end | |
def from_sharing_id(encoded_base_id) | |
encoded_base_id.to_i(SHARING_ID_BASE) / SHARING_ID_MULTIPLIER - SHARING_ID_ADDITION | |
end | |
end | |
# > u = User.new(1) | |
# => #<User:0x100351f50 @id=1> | |
# > u.sharing_id | |
# => "95e" | |
# > User.from_sharing_id("95e") | |
# => 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment