Skip to content

Instantly share code, notes, and snippets.

@h2rd
Last active August 29, 2015 14:16
Show Gist options
  • Select an option

  • Save h2rd/155db5fa3874b903dc81 to your computer and use it in GitHub Desktop.

Select an option

Save h2rd/155db5fa3874b903dc81 to your computer and use it in GitHub Desktop.
Ruby concerns example
# app/models/model_name.rb
class ModelName < ActiveRecord::Base
include Tokenable
end
# app/models/concerns/tokenable.rb
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment