在 shell 脚本中禁用颜色的惯用设计
我正在编写一个脚本,向用户呈现某种输出。我希望输出是彩色的,但也可以选择禁用它。
示例
$ ./run_script
Some output. <-- pretend this text is in blue
$ ./run_script --no-color
Some output <-- no color
目前,我开始使用 colored ruby gem 进行编程,所以我正在做这样的事情:
puts "Some output".blue
但是现在我开始意识到这是一个糟糕的方法,因为我需要某种功能来禁用颜色。
我猜解决这个问题的方法是 委托模式,我可以在其中传递文本哈希的形式 {:text =>; “一些输出”,:color => "blue"}
到 Outputter
类,该类仅屏蔽 ColorOutputter
类或 NoColorOutputter
类。 然而,我不太确定,因为为相对琐碎的事情创建三个新类似乎几乎是浪费。有谁有更好的方法来解决这个问题?
I am programming a script that presents some sort of output to the user. I would like output to be in color, but also have the option to disable it.
Example
$ ./run_script
Some output. <-- pretend this text is in blue
$ ./run_script --no-color
Some output <-- no color
Currently, I started programming with the colored ruby gem, so I'm doing stuff like this:
puts "Some output".blue
But now I'm starting to realize that this is a bad approach since I need some sort of functionality to disable the color.
I'm guessing a way to tackle this would be the delegation pattern where I could pass the text in the form of a hash {:text => "Some output", :color => "blue"}
to an Outputter
class which just masks either a ColorOutputter
class or NoColorOutputter
class.
Yet, I'm not quite sure as it seems almost wasterful to create three new classes for something relatively trivial. Does anyone have a better approach to resolving this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我实际上对我的输出类进行了切换。我所说的开关是指开/关着色输出。
在我看来,为一项小任务创建一堆继承类比在输出器类中使用开关更糟糕(以及通过使用此类开关获得的所有设计缺陷)
I actually did a switch on my outputter class. By switch I mean something to On/Off coloring ounput.
Creating a bunch of inherited classes for one small task in my opinion is worse than to have a switch in your outputter class (and all bad of design that you gain by using such switch)