now available

now available
Want fresh tech tips in your inbox?

Email Obfuscation and Extraction from Text with Rails


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)
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 w/ #email #hyperlinking #obfuscation #parsing #recipes #regex #regular expressions #securityruby on rails

Apps I've Built

XPath Expression Editor
Practice and improve your XPath skills with XPath Editor
Click to buy on the App Store
Photo Location Changer
Easily change the location on your photos and videos
Click here for more info about the app
Photo Date Changer
Easily change the dates and times on your photos and videos
Click here for more info about the app
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app