Skip to content

Instantly share code, notes, and snippets.

@r38y
Created January 11, 2015 01:52
Show Gist options
  • Save r38y/dcd62b221db17a1ea495 to your computer and use it in GitHub Desktop.
Save r38y/dcd62b221db17a1ea495 to your computer and use it in GitHub Desktop.
Tokenable with settable token name
class Discussion < ActiveRecord::Base
include Tokenable
set_token_field_name :other_token_name
end
module Tokenable
extend ActiveSupport::Concern
included do
before_validation :set_token, on: :create, unless: :token?
validates :token, uniqueness: true
set_token_field_name :token
end
def to_param; send(self.class.token_field_name); end
private
def set_token
self.send("#{self.class.token_field_name}=", SecureRandom.hex(5))
end
module ClassMethods
attr_accessor :token_field_name
def set_token_field_name(name)
self.token_field_name = name
end
def t(token)
find_by(token_field_name => token)
end
def t!(token)
find_by!(token_field_name => token)
end
def [](token)
t(token)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment