Created
August 1, 2012 21:10
-
-
Save bostonaholic/3230787 to your computer and use it in GitHub Desktop.
Rails models with generated hex as parameter instead of id
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 Hexable | |
def self.included(base) | |
base.class_eval do | |
before_create :generate_hex | |
attr_accessible :hex | |
end | |
end | |
def to_param | |
self.hex | |
end | |
private | |
def generate_hex | |
self.hex = SecureRandom.hex | |
end | |
end |
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
class Post < ActiveRecord::Base | |
include Hexable | |
end |
Hi there, this was really helpful! Quick question, how would you prevent collisions if the hex must be unique? Would you use a validator and have it up to the client to try again if there is a collision, or attempt to try again?
I actually just found a great way of doing this on SO. Here's the code:
module Tokenable
extend ActiveSupport::Concern
included do
before_create :generate_token
end
protected
def generate_token
self.token = loop do
random_token = SecureRandom.urlsafe_base64(nil, false)
break random_token unless self.class.exists?(token: random_token)
end
end
end
I'm sure you could use the hex in place of the base64, but your odds of running into a collision is greater and you have a lower limit of things you can store naturally.
Cheers!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
and for Rails 4