Skip to content

Instantly share code, notes, and snippets.

@daveknapik
Created September 12, 2013 18:09
Show Gist options
  • Save daveknapik/6541611 to your computer and use it in GitHub Desktop.
Save daveknapik/6541611 to your computer and use it in GitHub Desktop.
Rake task to format url() calls in stylesheets to the Rails 3.1+ image-url sass helper as well as clean up the url in the process
desc "Replaces and reformats url() calls in .scss files with image-url()"
task :format_stylesheets_for_asset_pipeline do
regex = /(url)\(('?|"?)(\/images\/)([^"']*)('?|"?)\)/
Dir.glob("app/assets/stylesheets/**/*.scss") do |filename|
unless File.directory?(filename)
output = ""
lines = []
file = File.open(filename, "r")
file.each_line do |line|
if m = regex.match(line)
replaced_line = line.sub(regex,'image-url("' + m[4] + '")')
lines << replaced_line
output += "found match: #{m[4]}\noriginal line: #{line}replaced line: #{replaced_line}\n"
else
lines << line
end
end
file.close
file = File.open(filename, "w")
lines.each {|line| file.write line}
file.close
puts "In #{filename}:\n\n" + output + "\n\n" if output.present?
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment