My rails mailer knows request and current_user

How about accessing @request and @current_user in your mailer

# config/initializers/mailer_knows.rb
module MailerBefore
def before(hash)
hash.keys.each do |key|
define_method key.to_sym do
eval " @#{key} = hash[key] "
class ActionMailer::Base
extend MailerBefore
class ActionController::Base
before_filter :mailer_knows
def mailer_knows
:request => request,
:current_user => (current_user and current_user.dup)

view raw


hosted with ❤ by GitHub

DRYing if @current_user.nil?

While working on one of rails applications, as I usually tend to check whether user is logged in, specially in views as follows

<% if @current_user.nil? %>
  <a href='url to login page'>
<% else %>
  <a href='some url where logged in user have access'>
<% end %>

And over some period I found this pattern repeating everywhere.

I thought of DRYing it, I wanted to have a kind of before_filter for every link that appear on the page, every link should go for login if that page or feature require user entity. and this should be handled by a common thing, similar to before_filter: login_require, on server side. I intend to achieve similar in views. A while back when I read up about html5 custom data attribute, and unobtrusive javascript etc, referring to them, I got one idea as described below, though it is not something that I am making use of custom data attribute exactly, but I found this idea useful and working. May be someone would have good suggestions here for me.

I will put any link which require user login as follows

<a href="/feature/page/" login-require >Feature</a>

And then I will have my after_load.js which will have the following event binding

jQuery('a[login-require]').bind('click', function() {
  <% if @current_user.nil? %>
    return false;
  <% else %>
    return true;
  <% end %>