In /lib I have a test_module.rb file with:
require 'digest'
module TestModule
def encrypt(string)
Digest::SHA2.hexdigest(string)
end
end
Now in my User.rb I have:
class user < ActiveRecord:Base
before_save :set_password
private
def set_password
self.encrypted_password = TestModule::encrypt(password)
end
end
How can I get access to this method, right 开发者_StackOverflow社区now I'm getting an error saying encrypt is not a method (undefined).
Do I require or include this module?
I just want to call the method ecrypt like its a static method really, advice?
instead of def encrypt
in your module, do def self.encrypt
. Explaining this the easy way, prefixing the name with self will make it a static function. Its actually a bit more complex then that, you are defining encrypt on the singleton class of the instance of Module stored in the constant TestModule, but that sort of thing is squarely in advanced ruby territory. You can think of self methods as static and not really get into any trouble.
精彩评论