Skip to content

Instantly share code, notes, and snippets.

@takuma-saito
Last active May 3, 2020 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takuma-saito/9ddb373186197d7e3cb485cfb439c80a to your computer and use it in GitHub Desktop.
Save takuma-saito/9ddb373186197d7e3cb485cfb439c80a to your computer and use it in GitHub Desktop.
has_secure_password.rb
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