Shorts. by Jeff Kreeftmeijer

Ruby: Set a random token after model initialization

Whenever I need to add random tokens to models on initialization, I search other projects and find this concern and include it:

module Concerns::Token
  def self.included(base)
    base.after_initialize(:set_token)
  end

  def set_token
    self.token = SecureRandom.hex if new_record?
  end
end

Now, when I need to add tokens to the model, I add the model name to the array in test/models/concerns/token_test.rb:

require_relative '../../test_helper'

describe Concerns::Token do
  [Session, Discussion, Comment, Notification].each do |model|
    describe "for a #{model}" do
      it "automatically generates a token" do
        model.new.token.length.should == 32
      end
    end
  end
end

And include Concerns::Token in the model:

class Notification < ActiveRecord::Base
  include Concerns::Token
end