Accessing the current request object on your mailer templates to generate links

A common issue with mailer templates is that as they’re not being called from a controller you can’t get your hands on the request object and access properties like host_with_port. While you’re usually calling the mailers inside controllers and you could possibly hand the request as a parameter to it, it isn’t really nice to do this every time you need to send an email.

<%= link_to 'Home', "#{current_request.protocol}#{current_request.host_with_port}/home" %>

So, if you’re looking for a quick and easy solution to this issue, the current_request plugin is your friend, you can install it by calling:

ruby script/plugin install git://

The plugin works by setting the current request in a thread local variable that will be available until the end of the request, which means that you can use it safely in your templates, two new methods are added to all views, current_request, that returns, obviously, the current request being answered and current_host that will build the current host with port and protocol for you. Examples:

Or you can just use a shorthand to the current host:

< %= link_to 'Home', "#{current_host}/home" %>

You can also use it wherever you want to access the current request (and not only on templates) by calling:


Comments or questions? Ping me on Twitter!