Module: TokenAttr::ClassMethods

Defined in:
lib/token_attr.rb

Instance Method Summary collapse

Instance Method Details

#token_attr(attr_name, options = {}) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/token_attr.rb', line 29

def token_attr(attr_name, options = {})
  token_attributes << attr_name

  define_method "should_generate_new_#{attr_name}_token?" do
    send(attr_name).blank?
  end

  define_method "generate_new_#{attr_name}_token" do
    token_length = options.fetch(:length, DEFAULT_TOKEN_LENGTH)

    if alphabet = options[:alphabet]
      alphabet_array = case alphabet
      when :alphanumeric
        ALPHANUMERIC_ALPHABET
      when :alphabetic
        ALPHABETIC_ALPHABET
      when :numeric
        NUMERIC_ALPHABET
      else
        alphabet.split('')
      end
      (0...token_length).map{ alphabet_array.sample }.join
    else
      hex_length = (token_length / 2.0).ceil # 2 characters per length
      SecureRandom.hex(hex_length).slice(0...token_length)
    end
  end
end

#token_attributesObject



58
59
60
# File 'lib/token_attr.rb', line 58

def token_attributes
  @token_attributes ||= []
end