【问题标题】:Two Ruby gems using the same namespace使用相同命名空间的两个 Ruby gem
【发布时间】:2018-05-25 14:06:12
【问题描述】:
我正在创建两个封装相同 API 的 gem。一个是仅包装 API 端点的普通客户端库,第二个与第三方 API 集成,并在第一个之上提供另一层抽象。它们没有任何重叠的方法。
第二个扩展第一个的命名空间是否可以接受?
例如:
# vanilla client lib
module Foo
class Bar
def do_bar
puts "Bar!"
end
end
end
# more complex client lib
module Foo
class Baz
def do_baz
puts "Baz!"
end
end
end
基于this question,AWS 似乎可以做到这一点。有没有可以和不可以的情况?
【问题讨论】:
标签:
ruby-on-rails
ruby
namespaces
【解决方案1】:
这似乎是一种完全可以接受的方式来构建您的宝石。在您的代码示例中,Foo::Bar 和Foo::Baz 将是同一命名空间中的两个完全不同的类,它们不会相互冲突。即使您在两个类中使用相同的方法名也是如此:
module Foo
class Bar
def do_thing
puts "Bar!"
end
end
end
module Foo
class Baz
def do_thing
puts "Baz!"
end
end
end
在这个修改后的示例中,Foo::Bar#do_thing 将输出 "Bar!",Foo::Baz#do_thing 将输出 "Baz!",因为它们是不同类中的不同方法。这种方法允许您将 Foo::Baz 对象换成 Foo::Bar 对象以更改行为,因为它们具有相同的接口。
如果您希望您的第三方 API gem 扩展您的 vanilla API gem 的功能,您可能需要考虑调整您的方法以使用继承。