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)
    }
  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

Related posts:

  1. Sending eMail with Rails on Mac OS X Development Environment
  2. Rails Helper to Remove Leading Zero in 12 Hour Time Format
  3. How to Install Ferret, the Full Text Search Engine with Your Rails Application
  4. Extending Rails Form Builders
  5. TinyMCE Rich Text Editor: HELLO EDITOR Plugin Tutorial and Example

1 Comments

  1. Nice one.

    Those having no access to Rails would also find it handy to use a manual tool for obfuscation that works very much like this one above or the one bundled in Smarty template engine: obfuscatr. It’s a Mac OS X Dashboard widget that uses JavaScript to encode the email addy. Read more about it.



Add Your Comment