开发者

ANSI escape code with html tags in Ruby?

开发者 https://www.devze.com 2023-02-08 06:00 出处:网络
Interestingly there are built-in ansi escape code in Ruby. There is also a more开发者_运维技巧 powerful version from a gem.

Interestingly there are built-in ansi escape code in Ruby.

There is also a more开发者_运维技巧 powerful version from a gem.

Unfortunately, these logs output to the console. My text is shown in the page so I need HTML tags to wrap around my text.

Would you guys have any idea how to go about it?


I guess what you want is to transform from escape characters to HTML.

I did it once by assuming the following code/colour hash for escape characters:

{ :reset          =>  0,
  :bright         =>  1,
  :dark           =>  2,
  :underline      =>  4,
  :blink          =>  5,
  :negative       =>  7,
  :black          => 30,
  :red            => 31,
  :green          => 32,
  :yellow         => 33,
  :blue           => 34,
  :magenta        => 35,
  :cyan           => 36,
  :white          => 37,
  :back_black     => 40,
  :back_red       => 41,
  :back_green     => 42,
  :back_yellow    => 43,
  :back_blue      => 44,
  :back_magenta   => 45,
  :back_cyan      => 46,
  :back_white     => 47}

What I did was the following conversion (far away from being anyhow optimized):

def escape_to_html(data)
  { 1 => :nothing,
    2 => :nothing,
    4 => :nothing,
    5 => :nothing,
    7 => :nothing,
    30 => :black,
    31 => :red,
    32 => :green,
    33 => :yellow,
    34 => :blue,
    35 => :magenta,
    36 => :cyan,
    37 => :white,
    40 => :nothing,
    41 => :nothing,
    43 => :nothing,
    44 => :nothing,
    45 => :nothing,
    46 => :nothing,
    47 => :nothing,
  }.each do |key, value|
    if value != :nothing
      data.gsub!(/\e\[#{key}m/,"<span style=\"color:#{value}\">")
    else
      data.gsub!(/\e\[#{key}m/,"<span>")
    end
  end
  data.gsub!(/\e\[0m/,'</span>')
  return data
end

Well, you will need fill the gaps of the colours I am not considering or backgrounds. But I guess you can get the idea.

Hope it helps


Thank you for the link to a cool gem I had not seen. I think what you are looking for, however, is termed Cascading Style Sheets (CSS). Because that google search will bring up about every other page cached on the internet, here are a few links for you that should get you started:

  • http://www.w3schools.com/css/default.asp - start with the most basic stuff.
  • http://guides.rubyonrails.org/layouts_and_rendering.html
  • http://rorrocket.com/ - generalized tutorials
  • http://nubyonrails.com/articles/dynamic-css - this may or may not be useful but a brief glance might provide some more rails like info on css, including SASS*.

*SASS is a ruby-ized abstraction to CSS used very frequently with ruby/rails

0

精彩评论

暂无评论...
验证码 换一张
取 消