Skip to content

Commit

Permalink
refactor escape and unescape methods
Browse files Browse the repository at this point in the history
  • Loading branch information
melborne committed Aug 30, 2010
1 parent 68a37d3 commit 51b68e7
Showing 1 changed file with 9 additions and 18 deletions.
27 changes: 9 additions & 18 deletions lib/termcolor.rb
Expand Up @@ -18,28 +18,19 @@ def parse(text)
end

def escape(text)
text.gsub(/[&<>'"]/) do | match |
case match
when '&' then '&amp;'
when '<' then '&lt;'
when '>' then '&gt;'
when "'" then '&apos;'
when '"' then '&quot;'
end
end
escape_or_unescape(:escape, text)
end

def unescape(text)
text.gsub(/&(lt|gt|amp|quot|apos);/) do | match |
case match
when '&amp;' then '&'
when '&lt;' then '<'
when '&gt;' then '>'
when '&apos;' then "'"
when '&quot;' then '"'
end
end
escape_or_unescape(:unescape, text)
end

def escape_or_unescape(dir=:escape, text)
h = Hash[*%w(& &amp; < &lt; > &gt; ' &apos; " &quot;)]
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>')
Expand Down

0 comments on commit 51b68e7

Please sign in to comment.