diff --git a/lib/termcolor.rb b/lib/termcolor.rb index 6fd1b6e..8a16bd3 100644 --- a/lib/termcolor.rb +++ b/lib/termcolor.rb @@ -18,28 +18,19 @@ def parse(text) end def escape(text) - text.gsub(/[&<>'"]/) do | match | - case match - when '&' then '&' - when '<' then '<' - when '>' then '>' - when "'" then ''' - when '"' then '"' - end - end + escape_or_unescape(:escape, text) end def unescape(text) - text.gsub(/&(lt|gt|amp|quot|apos);/) do | match | - case match - when '&' then '&' - when '<' then '<' - when '>' then '>' - when ''' then "'" - when '"' then '"' - end - end + escape_or_unescape(:unescape, text) + end + + def escape_or_unescape(dir=:escape, text) + h = Hash[*%w(& & < < > > ' ' " ")] + h = h.invert if dir == :unescape + text.gsub(/(#{h.keys.join('|')})/){ h[$1] } end + private :escape_or_unescape def prepare_parse(text) tag_separate text.gsub(/<(\/?)(\d+)>/, '<\1_\2>')