rails: building urls to static html in public dir

In rails when you create links in your view it’s best to use link_to or url_for tags when creating urls. However, both of these methods take as arguments the controller and/or action to generate a link for. If you’re trying to link to something in the public directory, like a static html file, then there is no controller or action. Instead of hardcoding the link, use compute_public_path:

<%=compute_public_path('file-name-without-extention','parent-dir','extension')%>

So if you’re trying to link to a file public/static_files/foo.html just do:

<%=compute_public_path('foo','static_files','html')%>


2 Responses to “rails: building urls to static html in public dir”

  • Liam Clancy (metafeather) Says:

    Good little tip.

    Any ideas on how got get mod_alias type behaviour using this - I searched all over.

    E.g. using compute_public_path with/without routes.rb so that:

    gets served from RAILS_ROOT/vendor/plugins/mycustomplugin/images/image.png rather than from RAILS_ROOT/public/images/image.png

    I would have thought this was common place but can’t find anything?

  • Ben Says:

    I’m not sure you can load images from plugins in your vendor directory (I could be wrong). What you could do is write a generator for your plugin that moves the images to a directory under /public.

Leave a Reply