Written by Sean Behan on Sun Jun 17th 2012

There is a helper method for handling the obfuscation of email addresses in Rails.

mail_to "me@domain.com", "My email", :encode => "hex"
 # => My email
If you want to then extract an email address(or all email addresses) from a block of text here is the code. I created a helper function called "emailitize" and put it in the ApplicationHelper module inside helpers/application_helper.rb
module ApplicationHelper
  #takes a string and will return the same string but with email addresses encoded and hyperlinked
  def emailitize(text)
    text.gsub(/([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})/i) {|m|
        mail_to(m, m.gsub("@", "[at]"), :encode=>:hex)
    }
  end
end
It's important to remember that you'll need to pass a block to the gsub method. You can't do something like this instead
text.gsub( /([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})/i, mail_to('\\1@\\2', '\\1@\\2', :encode=>:hex) )
It will work except the encode will fail. It will evaluate the '\\1@\\2' strings rather than as dynamic variables.

You can then use this function in your views

<%= emailitize @job.how_to_apply %>

More information is available in the Rails and Ruby docs: http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#M001887 http://ruby-doc.org/core/classes/String.html#M000817


Tagged with..
#email #hyperlinking #obfuscation #parsing #recipes #regex #regular expressions #security #Ruby on Rails

Just finishing up brewing up some fresh ground comments...