
[英]Ruby on Rails 2.3.8: Testing: Instance Variable Nil, when declared at top of class?
[英]Ruby class extension in Rails works when declared locally, returns `nil` when imported from `/lib/`
TLDR:哈希扩展程序可以完美地工作,当将其本地包含在我的Mailer中时,可以返回所需的输出,但是,即使成功加载了类方法,从lib/
的模块导入时,它也始终返回nil
。
当我在类定义之前在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
您需要在类之外将自定义方法注入到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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.