Created
June 29, 2009 12:48
-
-
Save EddM/137601 to your computer and use it in GitHub Desktop.
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
class HTMLColor | |
attr_accessor :hex, :red, :green, :blue | |
Colors = %w(red green blue) | |
Spectrum = %w(white black grey) + Colors | |
def initialize(hex) | |
@hex = hex.gsub(/#|0x/, "") | |
@red = @hex[0..1].hex | |
@green = @hex[2..3].hex | |
@blue = @hex[4..5].hex | |
end | |
Colors.each { |color| | |
define_method("#{color}!") { |val| | |
instance_variable_set("@#{color}", instance_variable_get("@#{color}") + val) | |
} | |
define_method("#{color}?") { | |
val = instance_variable_get("@#{color}") | |
other_colors = Colors.select { |c| c != color } | |
val > send(other_colors.first) && val > send(other_colors.last) | |
} | |
} | |
def white? | |
@red == 255 && @green == 255 && @blue == 255 | |
end | |
def black? | |
@red == 0 && @green == 0 && @blue == 0 | |
end | |
def grey? | |
!black? && !white? && @red == @green && @green == @blue | |
end | |
def main_color | |
Spectrum.each { |color| | |
return color if send("#{color}?") | |
} | |
end | |
def primary_color? | |
Colors.include?(main_color) | |
end | |
def lighter!(value = 10) | |
@red += value | |
@green += value | |
@blue += value | |
end | |
alias :white! :lighter! | |
def darker!(value = 10) | |
@red -= value | |
@green -= value | |
@blue -= value | |
end | |
alias :black! :darker! | |
def saturate!(value = 10) | |
send("#{main_color}!", value) if main_color != 'grey' | |
end | |
def to_s(txt = "#") | |
Colors.each { |color| txt << "%02X" % instance_variable_get("@#{color}") } | |
txt | |
end | |
alias :hex :to_s | |
def to_a | |
[@red, @green, @blue] | |
end | |
def to_h | |
{ :red => @red, :green => @green, :blue => @blue } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment