2

我正在创建一个为String类添加新方法的 gem。例如,如果我正在创建一个添加to_foobaron的方法,String我知道我可以简单地执行以下操作:

class String
  def to_foobar
    # ...
  end
end

但这是正确的方法还是有更好的方法?

4

2 回答 2

5

我会选择

# my_gem/lib/my_gem/core_extensions/string.rb

module MyGem::CoreExtensions::String
  def to_foobar
    # ...
  end
end

class String
  include MyGem::CoreExtensions::String
end

这样,如果我收到一条错误消息提到String#to_foobar,我不必怀疑“等等,String没有to_foobar方法,这是从哪里来的?” 我只能说

String.ancestors
# => [String, MyGem::CoreExtensions::String, Comparable, Object, Kernel]

Et voilà, there's this suspicious looking module in the ancestry chain, which, following standard Ruby naming conventions, probably lives in my_gem/lib/my_gem/core_extensions/string.rb.

Or, I can say

''.method(:to_foobar).owner
# => MyGem::CoreExtensions::String

And actually get a meaningful answer.

Of course,

''.method(:to_foobar).source_location
# => ['my_gem-0.0.1/lib/my_gem/core_extensions/string.rb", 4]

always works.

于 2012-06-11T00:17:14.490 回答
0

是的,这完全没问题。如果您不知道如何从头开始制作宝石,我建议您看一下珠宝商

于 2012-06-10T22:58:19.487 回答