Last active
May 3, 2020 12:49
-
-
Save tsaito-cyber/9ddb373186197d7e3cb485cfb439c80a to your computer and use it in GitHub Desktop.
has_secure_password.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'digest/md5' | |
module SecurablePassword | |
def self.included(base) | |
base.extend(ClassMethods) | |
end | |
module ClassMethods | |
def has_secure_password(name = :password) | |
include HasSecurePassword.new(name) | |
end | |
class HasSecurePassword < Module | |
def initialize(name) | |
attr_reader name | |
attr_accessor :"#{name}_digest" | |
define_method("#{name}=") do |value| | |
self.send("#{name}_digest=", Digest::MD5.hexdigest(value)) | |
end | |
define_method("authenticate?") do |value| | |
self.send("#{name}_digest") === Digest::MD5.hexdigest(value) | |
end | |
end | |
end | |
end | |
end | |
class Model | |
include SecurablePassword | |
has_secure_password(:password) | |
end | |
model = Model.new | |
model.password = "1234" | |
p model.authenticate?("abc") | |
p model.authenticate?("1234") | |
p model.password_digest |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment