Colors in irb / rails console

rails-console, ruby, ruby-on-rails

Solution

Try this:

text = 'red text'
puts "\033[31m#{text}\033[0m"

Another option is to extend String class

class String
  def red
    "\033[31m#{self}\033[0m"
  end

  def green
    "\033[32m#{self}\033[0m"
  end
end

Then you could do something like `'spinach'.green`

Problem

I'm testing a gem that outputs color in the terminal: ``` module Color def self.colorize(text, color_code) "#{color_code}#{text}e[0m" end def self.red(text) self.colorize(text, "\033[1;31;12m") end end ``` I have a testing file in the same directory, called color_test.rb: ``` require_relative 'color.rb' puts Color.red('I should be red') ``` This results in the following: ``` $ ruby color_test.rb I should be red ``` And the test is actually red. Horray. However, the same is not happening in the rails console: ``` $ rails c Loading development environment (Rails 4.1.1) 2.0.0-p247 :001 > require 'color' => true 2.0.0-p247 :003 > Chroma.colourise('text',"\033[1;31;12m") => "\e[1;31;12mtexte[0m" ``` So how do I escape it? (If that's even the term :P) I want to be able to display bold text and other styles in the console as well. This is just for testing, so I'm okay with downloading some sort of extension for the rails console, however if there's a way to package this functionality in the gem and give the console colors, that would be pretty cool so if someone could show me how I'd be glad.

Original source