简体   繁体   中英

/lib folder has a moduel test_module.rb, how to reference from my User.rb model?

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM