用于在 Ruby 中构建空对象类的工具包
快速介绍 Naught ------------------------ #### 现在这一切是什么呢? Naught 是用于在 Ruby 中构建 空对象 的工具包。 #### 这到底是什么意思? 空对象可以让你的代码更加 自信。 以下是一个不太自信的方法。 ruby class Geordi def make_it_so(logger = nil) logger && logger.info("Reversing the flux phase capacitance!") logger && logger.info("Bounding a tachyon particle beam off of Data's cat!") logger && logger.warn("Warning, bogon levels are rising!") end end 现在,请观察我们如何通过空对象模式为它注入一丝自信! ```ruby
class NullLogger
def debug(); end
def info(); end
def warn(); end
def error(); end
def fatal(*); end
end
class Geordi
def make_it_so(logger = NullLogger.new)
logger.info "Reversing the flux phase capacitance!"
logger.info "Bounding a tachyon particle beam off of Data's cat!"
logger.warn "Warning, bogon levels are rising!"
end
end
``` 通过提供一个 NullLogger,该对象实现了 Logger 接口中的 [一些] 为空操作,我们摆脱了那些不雅观的 && 运算符。 #### 这很简单。 我为什么需要为它创建一个库呢? 你不需要!空对象模式在核心上非常简单。
[][gem] [][test] [][lint] [][docs] [][typecheck] [gem]: https://rubygems.org/gems/naught [test]: https://github.com/avdi/naught/actions/workflows/test.yml [lint]: https://github.com/avdi/naught/actions/workflows/lint.yml [docs]: https://github.com/avdi/naught/actions/workflows/docs.yml [typecheck]: https://github.com/avdi/naught/actions/workflows/typecheck.yml
暂无开放 Issues,或尚未同步最近议题。