lib/token_attr.rb in token_attr-0.0.1 vs lib/token_attr.rb in token_attr-0.1.0
- old
+ new
@@ -4,11 +4,13 @@
module TokenAttr
extend ActiveSupport::Concern
DEFAULT_TOKEN_LENGTH = 8.freeze
- DEFAULT_SLUG_ALPHABET = [('a'..'z'),('A'..'Z'),(0..9)].map(&:to_a).flatten.freeze
+ ALPHABETIC_ALPHABET = [('a'..'z'),('A'..'Z')].map(&:to_a).flatten.freeze
+ NUMERIC_ALPHABET = [(0..9)].map(&:to_a).flatten.freeze
+ ALPHANUMERIC_ALPHABET = [ALPHABETIC_ALPHABET, NUMERIC_ALPHABET].flatten.freeze
class TooManyAttemptsError < StandardError
attr_reader :attribute, :token
def initialize(attr_name, token, message = nil)
@@ -33,11 +35,19 @@
define_method "generate_new_#{attr_name}_token" do
token_length = options.fetch(:length, DEFAULT_TOKEN_LENGTH)
if alphabet = options[:alphabet]
- alphabet = DEFAULT_SLUG_ALPHABET if alphabet == :slug
- alphabet_array = alphabet.split('')
+ 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