Skip to content

Instantly share code, notes, and snippets.

@atomkirk
Created June 29, 2016 18:47
Show Gist options
  • Save atomkirk/9bf19e92c4667d47bfa91db5843a066f to your computer and use it in GitHub Desktop.
Save atomkirk/9bf19e92c4667d47bfa91db5843a066f to your computer and use it in GitHub Desktop.
token for temporary values
has_many :tokens, as: :tokenable, dependent: :destroy
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
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