Randomly generated password Rails 3.1

家住魔仙堡 提交于 2019-12-03 10:15:38
Frederick Cheung

Rails provides ActiveSupport::SecureRandom which either (depending on the Ruby version) is just a bridge to Ruby's SecureRandom or reimplemented it on older versions of Ruby (if my memory is correct SecureRandom was added in 1.8.7)

Now that all of the versions of Ruby that Rails supports have SecureRandom built-in ActiveSupport::SecureRandom is no longer needed and has been deprecated. SecureRandom itself is going nowhere -

require 'securerandom'
SecureRandom.hex(8)

should do fine (you might want to consider SecureRandom.urlsafe_base64 for a more compact representation of the same amount of actual randomness)

Here is one simple code for random password with lenth 8

rand_password=('0'..'z').to_a.shuffle.first(8).join

Hope it will help.

Sometimes things from Rails are deprecated because they duplicate functionality that has been added to Ruby core, and SecureRandom seems to be one of those things.

You can use any of those random generator methods to produce a one-time-use password.

To Create Random and unique token/password

class User < ActiveRecord::Base

  before_create :generate_password

  def generate_password
    self.password = loop do
      random_token = SecureRandom.urlsafe_base64
      # If you are using FFaker gem then you can use it otherwise
      # SecureRandom is great choice
      # random_token = FFaker::Internet.password
      break random_token unless User.exists?(password: random_token)
    end
  end
end

The main object here is to generate random token and do not repeat that token in the database. It can be really useful for some cases like generating unique token, unique invoice number, etc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!