Skip to content

Commit

Permalink
Added task to resolve relative URLs in CSS files with Rails asset_pat…
Browse files Browse the repository at this point in the history
…h helper.
  • Loading branch information
jimpo committed Dec 11, 2013
1 parent 520884a commit 857a345
Showing 1 changed file with 36 additions and 1 deletion.
37 changes: 36 additions & 1 deletion lib/tasks/bower.rake
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ namespace :bower do
perform false do
sh 'bower list'
end
end
end

namespace :update do
desc "Update existing components and uninstalls extraneous components"
Expand All @@ -40,6 +40,13 @@ namespace :bower do
end
end
end

desc "Resolve assets paths in bower components"
task :resolve do
perform false do
resolve_asset_paths
end
end
end

def perform remove_components = true, &block
Expand Down Expand Up @@ -133,3 +140,31 @@ def perform_command remove_components = true, &block
end if data && !data["dependencies"].empty?
end
end

def resolve_asset_paths
# Resolve relative paths in CSS
Dir['bower_components/**/*.css'].each do |filename|
contents = File.read(filename)
# http://www.w3.org/TR/CSS2/syndata.html#uri
url_regex = /url\(\s*['"]?(?![a-z]+:)([^'"\)]*)['"]?\s*\)/

# Resolve paths in CSS file if it contains a url
if contents =~ url_regex
directory_path = Pathname.new(File.dirname(filename))
.relative_path_from(Pathname.new('bower_components'))

# Replace relative paths in URLs with Rails asset_path helper
new_contents = contents.gsub(url_regex) do |match|
relative_path = $1
image_path = directory_path.join(relative_path).cleanpath
puts "#{match} => #{image_path}"

"url(<%= asset_path '#{image_path}' %>)"
end

# Replace CSS with ERB CSS file with resolved asset paths
FileUtils.rm(filename)
File.write(filename + '.erb', new_contents)
end
end
end

0 comments on commit 857a345

Please sign in to comment.