Skip to content

Instantly share code, notes, and snippets.

@shouichi
Created April 24, 2013 02:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shouichi/5449172 to your computer and use it in GitHub Desktop.
Save shouichi/5449172 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'securerandom'
# Example
# class User
# include GenerateTokenFor[:confirmation_token]
# end
#
# @user = User.new
# @user.confirmation_token #=> nil
# @user.save
# @user.confirmation_token #=> "1cf694f7-a0db-46f7-b98f-a50cbf443760"
module GenerateTokenFor
def self.[](column)
Module.new do
const_set(:COLUMN, column)
def generate_token!
send("#{self.class.const_get(:COLUMN)}=", SecureRandom.uuid)
end
end
end
end
class A
include GenerateTokenFor[:token]
attr_accessor :token
end
class B
include GenerateTokenFor[:confirmation_token]
attr_accessor :confirmation_token
end
a = A.new
p a.token
a.generate_token!
p a.token
b = B.new
p b.confirmation_token
b.generate_token!
p b.confirmation_token
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment