Module: Tokens::ActiveRecord::ClassMethods

Defined in:
lib/tokens/active_record.rb

Instance Method Summary collapse

Instance Method Details

#find_by_token(name, hash) ⇒ Object

Find object by token.

User.find_by_token(:activation, "abcdefg")


76
77
78
79
80
# File 'lib/tokens/active_record.rb', line 76

def find_by_token(name, hash)
  token = find_token(name: name.to_s, token: hash)
  return unless token
  token.tokenizable
end

#find_by_valid_token(name, hash) ⇒ Object

Find object by valid token (same name, same hash, not expired).

User.find_by_valid_token(:activation, "abcdefg")


86
87
88
89
90
# File 'lib/tokens/active_record.rb', line 86

def find_by_valid_token(name, hash)
  token = find_token(name: name.to_s, token: hash)
  return if !token || token.expired?
  token.tokenizable
end

#find_token(*args) ⇒ Object

Find a token

User.find_token(:activation, "abcdefg")
User.find_token(name: activation, token: "abcdefg")
User.find_token(name: activation, token: "abcdefg", tokenizable_id: 1)


58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/tokens/active_record.rb', line 58

def find_token(*args)
  if args.first.kind_of?(Hash)
    options = args.first
  else
    options = {
      name: args.first,
      token: args.last
    }
  end

  options.merge!(name: options[:name].to_s, tokenizable_type: self.name)
  Token.where(options).includes(:tokenizable).first
end

#generate_token(size) ⇒ Object

Generate token with specified length.

User.generate_token(10)


41
42
43
44
45
46
47
48
49
50
# File 'lib/tokens/active_record.rb', line 41

def generate_token(size)
  validity = Proc.new {|token| Token.where(:token => token).first.nil?}

  begin
    token = SecureRandom.hex(size)[0, size]
    token = token.encode("UTF-8")
  end while validity[token] == false

  token
end

#tokenizableObject

Set up model for using tokens.

class User < ActiveRecord::Base
  tokenizable
end


32
33
34
35
# File 'lib/tokens/active_record.rb', line 32

def tokenizable
  has_many :tokens, as: "tokenizable", dependent: :destroy
  include InstanceMethods
end