ruby - 没有核心扩展的 String 上的链式方法

标签 ruby

我正在寻找一种方法(或者可能是最佳实践)将各种方法链接到字符串对象上,而无需实际打开 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/

相关文章:

ruby - 集会 API : documentation list of fields for portfolio items?

python - Python 中 "sending messages to objects"的一个很好的例子是什么?

ruby-on-rails - 有没有更好的方法来记录每天某个属性的值?

ruby - 如何在 Travis-CI 上为 TensorFlow 构建共享库

Ruby:无法解析在 OS X 中导出为 CSV 的 Excel 文件

ruby-on-rails - Rails STI 和多级继承查询

python - 非开发人员在 Mac OS X 上管理开发人员系统的最佳实践

ruby-on-rails - 在 OS X 上调试 Ruby 2.1 的方法

ruby - 如何查询mongoid 'not_in' 'greater than'

ruby-on-rails - 将 3 个结果包装在一个 div 中