开发者

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

开发者 https://www.devze.com 2023-02-14 07:14 出处:网络
In /lib I have a test_module.rb file with: require \'digest\' module TestModule def encrypt(string) Digest::SHA2.hexdigest(string)

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号