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")


58
59
60
61
62
# File 'lib/tokens/active_record.rb', line 58

def find_by_token(name, hash)
  token = find_token(:name => name.to_s, :token => hash)
  return nil 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")


68
69
70
71
72
# File 'lib/tokens/active_record.rb', line 68

def find_by_valid_token(name, hash)
  token = find_token(:name => name.to_s, :token => hash)
  return nil 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)


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

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)


23
24
25
26
27
28
29
30
31
32
# File 'lib/tokens/active_record.rb', line 23

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

  begin
    token = SecureRandom.hex(40)[0, size]
    token = token.encode("UTF-8") if token.respond_to?(:encoding)
  end while validity[token] == false

  token
end

#tokenizableObject

Set up model for using tokens.

class User < ActiveRecord::Base
  tokenizable
end


14
15
16
17
# File 'lib/tokens/active_record.rb', line 14

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