我正在寻找一种方法(或者可能是最佳实践)将各种方法链接到字符串对象上,而无需实际打开 String
类。这是因为我想应用于 String 对象的转换完全是特定于项目的,我看不出有什么理由用它来污染全局空间。
有办法实现吗?也许是某种 wrapper ?我在一个实例变量上尝试了 gsub!
但 gsub!
除非 gsub
失败时抛出 nil
匹配,所以它停止了我想要实现的链接。
基本上,我需要能够做到:
"my_string".transformation1.transformation2.transformation3
并将所有这些转换保留在我的应用程序的命名空间中。有什么想法吗?
最佳答案
如果您使用的是 Ruby >= 2.0,您可以使用 refinements :
module MyRefinements
refine String do
def transformation1
# ...
self
end
def transformation2
# ...
self
end
def transformation3
# ...
self
end
end
end
# Either in global scope (active until the end-of-file)
# or in lexical scope (active until the lexical scope end)
# More on this in the refinements docs scope section
# global scope
using MyRefinements
"test".transformation1.transformation2.transformation3 #=> "test"
# lexical scope
begin
using MyRefinements
"test".transformation1.transformation2.transformation3 #=> "test"
end
关于ruby - 没有核心扩展的 String 上的链式方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21706496/