Alex Rivera | Logout

Fast Conversion HTML template to Rails Asset ERB/Sass layout

Asked 2012-12-12T02:58:24.900
9

I find myself constantly doing the same thing, using designers to create nice ui's then convert HTML/CSS to split across the asset pipeline and find and replace paths and css+js tags; updating everything to use the asset path. Is there something that automagically does this?

Edit
Report

1 Answer

5

To me, this situation just calls out loudly for sed. If you're running Linux, Mac OS X, or another *nix, read on. (If your dev environment is Windows but you are deploying to *nix server where you can set up post-deploy scripts, this approach will still work there.)

So your designer has access to your assets in local directories, and it'll generate tags like <img src="images/logo.png">. But, in deployment you want to either replace those paths with ERB calls like <img src="<%= asset_path 'logo.png' %>">, or else change them to point at some external CDN with a tag like <img src="http://assets.mysite.com/logo.png">, right?

Well, in either case, sed is your friend! Sed can (among other things) go through a file and apply regex substitutions to them in-place. In the ERB call situation (assuming you've already renamed your file to have an erb extension), you would run this command:

$ sed -i 's/\(<img[^>]*src="\)images/\([^"]+\)\("[^>*]>\)/\1<%= asset_path \'\2\' %>\3/g' somefile.html.erb

After running this command, somefile.html.erb will be using asset_path instead of manually specified image paths.

The second case, where you are providing images on another server or maybe just from another path, is similar:

$ sed -i 's/\(<img[^>]*src="\)images/\([^"]+\)\("[^>*]>\)/\1http:\/\/assets.mysite.com\/\2\3/g' somefile.html

And Bob's your uncle!

One thing that's annoying about these commands is that you have to run them on each and every file. Well, time for another UNIX utility to come to the rescue: find. This utility can run a script on a bunch of files in a directory tree:

$ find dir/with/html -type f -name '*.html.erb' -exec sed 's/foo/bar/g' {} \;
<
answered 2013-02-02T18:13:26.430

Your Answer