Forum: Ruby on Rails Generate random password in Rails

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Anatoly M. (Guest)
on 2009-01-06 15:53
http://www.railsgeek.com/2009/1/6/generate-random-...

I am using Restful_authentication plugin for one of my projects.
As part of my user creation workflow, system should to generate a random
password for the new user.
So, look at my password creation behaviour:

    * generate uncrypted password
    * send this with e-mail notification
    * crypt the password

<controller>
class CandidatesController < ApplicationController
  ...
  if @candidate.valid?
    candidate.save
    Notifier.deliver_inv(candidate.email, candidate.crypted_password)
    candidate.encrypt_password
  end
end

<model>
require 'digest/sha1'
class User < ActiveRecord::Base
  ...
  def encrypt_password
    self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{name}--")
    self.crypted_password = encrypt(self.crypted_password)
    save(false)
  end
  protected
    def save_password
      (self.crypted_password = password) unless self.crypted_password
    end
...
end

class Candidate < User
  # Callbacks:
  before_save :save_password
  before_validation_on_create Proc.new do |u|
    u.password = Array.new(12) { (rand(122-97) + 97).chr }.join
    u.password_confirmation = u.password
  end

end
This topic is locked and can not be replied to.