Created
April 7, 2011 17:04
-
-
Save timuruski/908211 to your computer and use it in GitHub Desktop.
TextMate command for toggling CSS color format through hex, RGB and RGBA
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
class Color < Struct.new(:r, :g, :b, :a) | |
def self.from_hex (str) | |
args = case str.length | |
when 3; str.scan(/[0-9a-f]/i).map{ |s| "#{s}#{s}".to_i(16) } | |
when 6; str.scan(/[0-9a-f]{2}/i).map{ |s| s.to_i(16) } | |
else [0, 0, 0] | |
end << 1.0 | |
new(*args) | |
end | |
def self.from_rgb (str) | |
new( *(str.split(',').map(&:to_i) << 1.0) ) | |
end | |
def self.from_rgba (str) | |
new(*(str.split(',')[0..2].map(&:to_i) << str.split(',')[-1].to_f)) | |
end | |
def to_hex | |
"##{"%02X" % r}#{"%02X" % g}#{"%02X" % b}" | |
end | |
def to_rgb | |
"rgb(#{r}, #{g}, #{b})" | |
end | |
def to_rgba | |
"rgba(#{r}, #{g}, #{b}, 1.0)" | |
end | |
end | |
print case str = STDIN.read | |
when /\A#([0-9a-f]{3,6})\z/i; Color.from_hex($1).to_rgb | |
when /\Argb\(([0-9., ]+)\)\z/i; Color.from_rgb($1).to_rgba | |
when /\Argba\(([0-9., ]+)\)\z/i; Color.from_rgba($1).to_hex | |
else str | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment