Monkey Patch Rails Core Concerns
-
26-06-2021 - |
Вопрос
I've bumped into a dead-end with the SecurePassword model of ActiveModel doing bcrypt only. (I need to store the passwords with a different but equally secure hash in order to export and use the hashed passwords for Dovecot IMAP auth.)
This may be a useful feature for everybody, so I'll work it into a patch eventually. But right now, I'd like to monkey patch the SecurePassword module. However, I'm not sure how to tackle this in such a way to make sure the concern is monkey patched before it's included anywhere else.
Thanks for your hints!
Решение
The easiest way to get started, in my experience (with Rails 3.2 at least, can't say for earlier versions since the last time I used Rails was in 2.x days) is to just save your code into a file such as secure_password.rb
under config/initializers
.
In config/initializers/secure_password.rb
, you can almost get away with anything, but in your case you probably want to go:
module ActiveModel
module SecurePassword
module InstanceMethodsOnActivation
def authenticate(unencrypted_password)
# Replace calls to BCrypt here
end
def password=(unencrypted_password)
# and here
end
end
end
end
See http://guides.rubyonrails.org/configuring.html for more on Rails initialization and configuration.
(Untested, but I've monkey-patched ActiveRecord::Timestamp
just like that and it all just works.)