Created
January 11, 2015 01:52
-
-
Save r38y/dcd62b221db17a1ea495 to your computer and use it in GitHub Desktop.
Tokenable with settable token name
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 Discussion < ActiveRecord::Base | |
include Tokenable | |
set_token_field_name :other_token_name | |
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
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