NOTE: The svn repository referenced here is no longer running. Hopefully you’re running an new enough version of Rails that this post isn’t necessary.
So, you’ve set up an asset host for your Rails application, but you have some files that that you don’t want to or can’t put on your asset host.
As an example, Plot-O-Matic creates images (of graphs) on the fly. If I had just blithely switched over to using asset hosting, then you wouldn’t see any changes when you updated a graph on Plot-O-Matic, as the Rails application only updates the graph image in its local public directory, and the asset host file remains unchanged.
You have a few options to fix this.
You could, of course, just use straight HTML tags to get at your local files, but that’s kind of just plain ugly.
You could just create the files in a directory that’s not in public. But then you can’t let people link to them easily, and you’re still not able to use asset tag helpers.
Finally, you could create a asset tag helper that created local links. That’s what I chose to do on Plot-O-Matic, and here’s how I did it.
Getting started
This will only work with the latest changes to the asset host code. There are two ways you can get this.
Upgrade to Rails 2.0
For instructions, scroll to the bottom of this post.
All this plugin does is monkeypatch in the multiple asset host functionality from Rails Edge.
Creating the helper
Let’s take a look at how the standard image tag helper works. The
following code is from vendor/rails/actionpack/lib/action_view/helpers/asset_tag_helper.rb.
The important part here is the line
This is where the path is calculated. Let’s take a closer look at the image_path method
OK, so all that that does is call compute_public_path. compute_public_path is the part that has been updated to work with multiple asset hosts:
Aha! So, all we need to do to get local calls is make a call to compute_public_path with include_host = false. Let’s create a local_image_tag helper that does just that. The following code should reside in RAILS_ROOT/app/helpers/application_helper.rb
This is too ugly. What we really want is to be able to create an image tag like this:
to do this, you would change the image_tag code to something like this