Skip to content

Instantly share code, notes, and snippets.

@bostonaholic
Created August 1, 2012 21:10
Show Gist options
  • Save bostonaholic/3230787 to your computer and use it in GitHub Desktop.
Save bostonaholic/3230787 to your computer and use it in GitHub Desktop.
Rails models with generated hex as parameter instead of id
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
class Post < ActiveRecord::Base
include Hexable
end
@chronick
Copy link

chronick commented Oct 6, 2013

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?

@chronick
Copy link

chronick commented Oct 6, 2013

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