1

我写了一个小模块lib/encryption/encryption.rb

module Encryption
  def self.encrypt(value)
    ...
  end

  def self.decrypt(value)
    ...
  end
end

我想在 Devise 的这两个文件中使用/访问这个模块,即:

  1. token_authenticable.rb
  2. 可验证的.rb

我已经通过创建 2 个新文件并将它们放入 /config/initilaizers 来覆盖它们(复制其中的原始源代码并修改它们)

  1. /config/initializers/token_authenticable.rb
  2. /config/initializers/authenticable.rb

例如,一个文件如下所示:

require 'devise/strategies/token_authenticatable'
require './lib/encryption/encryption.rb' #TRIED THIS, BUT DOES NOT WORK

module Devise
  module Models
    # The TokenAuthenticatable module is responsible for generating an authentication token and
    # validating the authenticity of the same while signing in.
    ...

我的修改工作,但我怎样才能在这些文件中访问我的 lib/Encryption.rb 模块?这种修改方法是最佳实践吗?如果没有,正确的方法是什么?

4

2 回答 2

2

如果你的 application.rb 中有这个:

config.autoload_paths += %W(#{config.root}/lib)

然后 '/lib' 将被自动加载。意思是你可以打电话

require 'encryption/encryption'

它应该工作。

于 2013-04-25T12:36:22.613 回答
0

在一个类中包装两个方法,例如 MyEncryptionAlgo。创建该类的对象

obj = Encryption::MyEncryptionAlgo.new

使用这个对象来访问这两个方法。

obj.encrypt(value)
obj.decrypt(value)
于 2013-04-25T12:30:23.237 回答