Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add example of conditionally requiring a password [ci-skip] #45754

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
25 changes: 24 additions & 1 deletion activemodel/lib/active_model/secure_password.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ module ClassMethods
#
# ==== Examples
#
# Using Active Record, which automatically includes ActiveModel::SecurePassword:
# ===== Using Active Record (which automatically includes ActiveModel::SecurePassword)
#
# # Schema: User(name:string, password_digest:string, recovery_password_digest:string)
# class User < ActiveRecord::Base
Expand Down Expand Up @@ -77,6 +77,29 @@ module ClassMethods
#
# user.authenticate("vr00m") # => false, old password
# user.authenticate("nohack4u") # => user
#
# ===== Conditionally requiring a password
#
# class Account
# include ActiveModel::SecurePassword
#
# attr_accessor :is_guest, :password_digest
#
# has_secure_password
#
# def errors
# errors = super
# errors.delete(:password, :blank) if is_guest
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd inline the exception with a tap, so: super.tap { |errors| errors.delete(:password, :blank) if is_guest }

# errors
# end
# end
#
# account = Account.new
# account.valid? # => false, password required
#
# account.is_guest = true
# account.valid? # => true
#
def has_secure_password(attribute = :password, validations: true)
# Load bcrypt gem only when has_secure_password is used.
# This is to avoid ActiveModel (and by extension the entire framework)
Expand Down