Module: HasRandomToken::ClassMethods
- Defined in:
- lib/has_random_token.rb
Instance Method Summary collapse
- #generate_random_token(attribute, unique, length) ⇒ Object
- #has_random_token(attribute: :token, unique: false, length: 32) ⇒ Object
Instance Method Details
#generate_random_token(attribute, unique, length) ⇒ Object
12 13 14 15 16 17 18 |
# File 'lib/has_random_token.rb', line 12 def generate_random_token(attribute, unique, length) begin token = SecureRandom.base64(length)[0 .. length - 1] end while unique && self.exists?(attribute => token) return token end |
#has_random_token(attribute: :token, unique: false, length: 32) ⇒ Object
5 6 7 8 9 10 |
# File 'lib/has_random_token.rb', line 5 def has_random_token(attribute: :token, unique: false, length: 32) require 'securerandom' define_method("regenerate_#{attribute}") { update! attribute => self.class.generate_random_token(attribute, unique, length) } before_create { self.send("#{attribute}=", self.class.generate_random_token(attribute, unique, length)) unless self.send("#{attribute}?")} end |