【问题标题】:Include or extend a class/module from a gem (e.g. devise)从 gem 中包含或扩展类/模块(例如设计)
【发布时间】:2013-04-19 07:46:02
【问题描述】:

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

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

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

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

  1. token_authenticable.rb
  2. authenticable.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 模块? 这种修改方法是最佳实践吗? 如果没有,正确的做法是什么?

【问题讨论】:

    标签: ruby-on-rails module devise


    【解决方案1】:

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

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

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

    require 'encryption/encryption'
    

    它应该可以工作。

    【讨论】:

    • 谢谢你,这行得通!我已经使用 config.autoload_paths += Dir["#{config.root}/lib/**/"] 将 /lib 添加到 config.autoload_paths
    【解决方案2】:

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

    obj = Encryption::MyEncryptionAlgo.new
    

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

    obj.encrypt(value)
    obj.decrypt(value)
    

    【讨论】:

    • 感谢您的帮助,但是如何在 /config/initializers/*.rb 文件中包含该类的模块? (见编辑过的问题)
    猜你喜欢
    • 2015-04-18
    • 2016-02-24
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    • 2020-04-25
    相关资源
    最近更新 更多