Cleaning up CSS with Ruby

I just created a small Ruby script that will remove duplicate classes/blocks from a css file.

For this to work the css blocks should be in the following form:

input{
	font:100% Arial, Helvetica, sans-serif;
	vertical-align:middle;
	color:#000;
}

Duplicate “inline” lines, ie.: class{ … } won’t be removed.

css 		= File.new('all.css', 'r')
blocks 		= []
new_css 	= ''
add_flg 	= true
while(line = css.gets)
	if line =~ /\{$/
		block = line.gsub(/\{/, '')
		if blocks.include? block
			add_flg = false
		else
			blocks << block
		end
	elsif (line =~ /\}$/ && add_flg == false) 
		add_flg = true
		line = line.sub(/\}$/, '')
	end

	if add_flg
		new_css += line
	end
end

File.open('all_fixed.css', 'w') {|f| f.write(new_css.gsub(/\n{3,}/, "\n")) }

As you can see we don’t care which copy should be kept, it will automatically be the first one.

We open the CSS file and:

1.) Start looping its lines.

2.) Check if a line contains a { at the end.

3.) If it does we remove the { character and check if the line already exists on our blocks array. If it does we set the add flag to false.

4.) If it doesn’t we add it to the blocks array.

5.) Next we check if the line contains a } signaling that we’re at the end of a block, in that case we set the add flag to true if it was false before.

6.) Finally we add the current line to the fixed file if the flag allows it.

7.) We save the new file but first we replace 3 or more newlines with one newline so we don’t get a lot of empty space where we’ve deleted dups.


Related Posts

Tags: ,