在 shell 脚本中禁用颜色的惯用设计

发布于 2024-10-14 15:28:43 字数 739 浏览 0 评论 0原文

我正在编写一个脚本,向用户呈现某种输出。我希望输出是彩色的,但也可以选择禁用它。

示例

$ ./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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

慕巷 2024-10-21 15:28:43

我实际上对我的输出类进行了切换。我所说的开关是指开/关着色输出。

在我看来,为一项小任务创建一堆继承类比在输出器类中使用开关更糟糕(以及通过使用此类开关获得的所有设计缺陷)

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文