Skip to content

Instantly share code, notes, and snippets.

@michaelwclark
Created November 16, 2012 22:07
Show Gist options
  • Select an option

  • Save michaelwclark/4091319 to your computer and use it in GitHub Desktop.

Select an option

Save michaelwclark/4091319 to your computer and use it in GitHub Desktop.
Ruby script I wrote to help me learn the language better. It is an echo like utility that utilizes english colors/modes for terminal output rather than complicated char codes. It's not fully polished or the most practical of tools, but it worked for what
#!/usr/bin/env ruby
#Usage:
# Echo.bold OutputString
#
# \e[z;XX;YYm
class TermFormat
@DEFAULTS ={
"FOREGROUND" => "green",
"BACKGROUND" => "none",
"MODE" => "normal"
}
@FOREGROUND=30
@BACKGROUND=40
@MODES ={ #blink won't work unless called from console in OSX
"normal" => 0,
"bold" => 1,
"underline" => 4,
"blink" => 5,
"invert" => 7
}
@COLORS={
"black" => 0,
"red" => 1,
"green" => 2,
"yellow" => 3,
"purple" => 4,
"magenta" => 5,
"blue" => 6,
"white" => 7,
"none" => 99
}
def initialize
ObjectSpace.define_finalizer( self, self.class.finalize )
end
def finalize
proc { reset }
end
def self.chkMode(mode)
@MODES.has_key?(mode)
end
def self.chkColor(color)
@COLORS.has_key?(color)
end
def self.reset
`echo \e[0;m`
end
def self.help
puts """Usage:
./Echo.rb mode bg fg msg
./Echo.rb mode fg msg
./Echo.rb fg msg
./Echo.rb msg"""
modeHelp
colorHelp
end
def self.modeHelp
puts "Valid Modes: "
puts "\t#{@MODES.keys.join(", ")}"
end
def self.colorHelp
puts "Valid Colors: "
puts "\t#{@COLORS.keys.join(", ")}"
end
def self.warning(msg)
puts "Warning!"
puts "\t#{msg}"
end
#Main
if ARGV.size > 0
argc = ARGV.size
msgIndex = 0
escIndex = -1
bgIndex = -1
fgIndex = -1
if argc == 2 && chkColor(ARGV[0])
fgIndex = 0
msgIndex = 1
end
if argc == 3 && chkMode(ARGV[0]) && chkColor(ARGV[1])
escIndex = 0
fgIndex = 1
msgIndex = 2
end
if argc >= 4 && chkMode(ARGV[0]) && chkColor(ARGV[1]) && chkColor(ARGV[2])
escIndex = 0
bgIndex = 1
fgIndex = 2
msgIndex = 3
end
fgColor = fgIndex >= 0 ? ARGV[fgIndex].to_s.downcase : @DEFAULTS["FOREGROUND"]
bgColor = bgIndex == 1 ? ARGV[bgIndex].to_s.downcase : @DEFAULTS["BACKGROUND"]
escCode = escIndex == 0 ? ARGV[escIndex].to_s.downcase : @DEFAULTS["MODE"]
e = @MODES[escCode]
f = fgColor != "none" ? "#{@COLORS[fgColor].to_i + @FOREGROUND};" : ""
b = bgColor != "none" ? "#{@COLORS[bgColor].to_i + @BACKGROUND};" : ""
msg = ARGV.slice(msgIndex,argc).join(" ")
#\e[0;32;31;mhello
puts "\e[#{e};#{f}#{b}m#{msg}"
else
help
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment