Module: TokenAttr::Concern::ClassMethods

Defined in:
lib/token_attr/concern.rb

Instance Method Summary collapse

Instance Method Details

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



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/token_attr/concern.rb', line 20

def token_attr(attr_name, options = {})
  token_definitions << TokenDefinition.new(attr_name, options[:scope])

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

  define_method "generate_new_#{attr_name}" 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_definitionsObject



49
50
51
# File 'lib/token_attr/concern.rb', line 49

def token_definitions
  @token_definitions ||= []
end