Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

arguments for String#termcolor #3

Closed
wants to merge 7 commits into from

2 participants

@melborne

タグ無しの文字列に対して、引数で色と位置を指定できるようにしてみました。
ちょっと思想が違うかも知れませんが、ご検討頂けるとうれしいです。

melborne

@jugyo
Owner

面白い提案ありがとうございます。
Rubyist はたぶんみんな文字列処理が大好きなので、この手の処理は自分で頑張ってやっちゃうと思うんですよね。
なので、あえて TermColor でやる必要はないかなぁと思いました。

@melborne

そうですね、TermColorの領域じゃない気もします。
検討ありがとうございます。

@melborne melborne closed this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
This page is out of date. Refresh to see the latest.
Showing with 28 additions and 2 deletions.
  1. +19 −2 lib/termcolor.rb
  2. +9 −0 spec/termcolor_spec.rb
View
21 lib/termcolor.rb
@@ -108,7 +108,24 @@ def to_esc_seq(name)
end
class String
- def termcolor
- TermColor.parse(self)
+ def termcolor(color=nil, target=nil)
+ tagging = ->s{ "<#{color}>#{s}</#{color}>" }
+ str =
+ if color
+ case target
+ when Range
+ dself = self.dup
+ dself[target] = tagging[(dself[target])]
+ dself
+ when String, Symbol
+ self.gsub(/#{target.to_s}/) { tagging[$&] }
+ else
+ tagging[self]
+ end
+ else
+ self
+ end
+
+ TermColor.parse(str)
end
end
View
9 spec/termcolor_spec.rb
@@ -89,5 +89,14 @@ module TermColor
TermColor.prepare_parse(combined).should == separated
end
end
+
+ it 'should do colorize using String#termcolor' do
+ "<red>ruby</red>".termcolor.should == "\e[31mruby\e[0m"
+ "ruby".termcolor(:red).should == "<red>ruby</red>".termcolor
+ "ruby isn't ruby gem".termcolor(:red, 11..14).should == "ruby isn't <red>ruby</red> gem".termcolor
+ "ruby isn't ruby gem".termcolor(:red, 'ruby').should == "<red>ruby</red> isn't <red>ruby</red> gem".termcolor
+ "ruby isn't ruby gem".termcolor(:red, :ruby).should == "<red>ruby</red> isn't <red>ruby</red> gem".termcolor
+ "Ruby isn't Ruby Gem".termcolor(:red, '[A-Z]+').should == "<red>R</red>uby isn't <red>R</red>uby <red>G</red>em".termcolor
+ end
end
end
Something went wrong with that request. Please try again.