Created
June 29, 2016 18:47
-
-
Save atomkirk/9bf19e92c4667d47bfa91db5843a066f to your computer and use it in GitHub Desktop.
token for temporary values
This file contains hidden or 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
has_many :tokens, as: :tokenable, dependent: :destroy |
This file contains hidden or 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 CreateTokens < ActiveRecord::Migration[5.0] | |
def change | |
create_table :tokens do |t| | |
t.string :token, null: false | |
t.references :tokenable, polymorphic: true, null: false | |
t.timestamps | |
end | |
end | |
end |
This file contains hidden or 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 Token < ApplicationRecord | |
belongs_to :tokenable, polymorphic: true | |
validates :token, presence: true | |
validates :tokenable, presence: true | |
before_validation on: :create do | |
self.token = SecureRandom.hex(12) | |
end | |
def self.claim(key, must = true) | |
token = Token.find_by(token: key) | |
if token | |
object = token.tokenable | |
token.destroy | |
return object | |
else | |
if must | |
raise ActiveRecord::RecordNotFound | |
else | |
return nil | |
end | |
end | |
end | |
def self.claim!(key) | |
self.claim(key, true) | |
end | |
def self.for(object) | |
Token.create!(tokenable: object) | |
end | |
def to_s | |
token | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment