Last active
December 29, 2015 02:19
-
-
Save polarblau/7599999 to your computer and use it in GitHub Desktop.
Extract all colors with Ruby from a stylesheet.
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
css = IO.read('application.css') | |
# find all hex color values | |
hex = css.scan(/#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})/).flatten.map(&:strip) | |
# convert the short code colors into long versions | |
hex.map! { |color| color.length == 3 ? (c = color.split('')).zip(c).join : color } | |
# find all rgb and rgba color values | |
rgb = css.scan(/(rgba?\(\d+,\s*\d+,\s*\d+(?:,\s*\d+(?:\.\d+)?)?\))/).flatten | |
# split rgba and rgb | |
rgba, rgb = rgb.partition {|value| value =~ /^rgba/ } | |
# convert rgb to hex | |
hex << rgb.map { |color| | |
color.match(/[\d,\s]+/)[0].split(',').map(&:strip).map { |value| | |
value.to_i.to_s(16).rjust(2, '0') | |
}.join('') | |
} | |
# join colors | |
colors = hex.flatten.map { |color| "##{color}" } + rgba | |
# ensure a unique color set | |
colors.uniq! | |
# print for insertion into Sass file with generic variable names | |
colors.each_with_index { |color, index| puts "$color_#{index}: #{color}" } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment