0

TLDR:哈希扩展工作完美,当本地包含在我的邮件程序中时返回所需的输出,但从nil模块导入时总是返回lib/,即使类方法已成功加载。

当我在我的 mailer.rb 文件中声明扩展时,在我的类定义之前,如下所示:

class Hash
  def try_deep(*fields)
    ...
  end
end

class MyMailer < ApplicationMailer
  some_hash.try_deep(:some_key)
end

它完美无缺,但这是不好的做法。我认为最好先声明扩展名,/lib/core_ext/hash/try_deep.rb然后在 Mailer 中要求它,如下所示:

/lib/core_ext/hash/try_deep.rb:

module CoreExtensions
  module Hash
    module TryDeep
      def try_deep(*fields)
        ...
      end
    end
  end
end

/my_mailer.rb:

require 'core_ext/hash/try_deep'

class MyMailer < ApplicationMailer
  Hash.include CoreExtensions::Hash::TryDeep
  some_hash.try_deep(:some_key)
end
4

1 回答 1

2

您需要将您的自定义方法注入到Hash您的类之外:

my_mailer.rb

require 'core_ext/hash/try_deep'

class Hash
  include CoreExtensions::Hash::TryDeep
end

class MyMailer < ApplicationMailer
  some_hash.try_deep(:some_key)
end
于 2018-11-15T03:41:16.090 回答