Reputation: 319
I'd like to obfuscate an email address on my webpage. I'm hoping to avoid JS in case my users deactivate it.
I found this gem: actionview-encoded_mail_to but it doesn't seem to work for me. It shows the full email address on the page (which is good), but it also shows it in the console.
I tried the 3 examples with the same result. The gem appears in my Gemfile so should be correctly installed.
Upvotes: 3
Views: 771
Reputation: 13531
You can always roll your own but, first, that gem definitely works. Here's what I did...
I added the gem to a Rails 4.2 app:
# Gemfile
gem 'actionview-encoded_mail_to'
I installed it:
$ bundle install
I entered the console:
$ rails console
I made the helper methods available in the console:
include ActionView::Helpers::UrlHelper
Called the mail_to
helper with the same arguments as the example:
mail_to "[email protected]", nil, replace_at: "_at_", replace_dot: "_dot_", class: "email"
...and got this result:
"<a class=\"email\" href=\"mailto:[email protected]\">me_at_domain_dot_com</a>"
That "me_at_domain_dot_com"
looks properly obfuscated. What steps did you take?
It would be a trivial string substitution to obfuscate an email string, we can just use sub
:
def obfuscate_email(email, replace_at: '_at_', replace_dot: '_dot_')
email.sub("@", replace_at).sub ".", replace_dot
end
I tested that out in the console:
obfuscate_email "[email protected]"
# => "me_at_example_dot_com"
You can place that method in application_helper.rb
and use it in any of your views:
link_to obfuscate_email(user.email), "mailto:#{user.email}"
# => "<a href=\"mailto:[email protected]\">me_at_example_dot_com</a>"
Note that the href must be the unobfuscated email in order for it to work properly.
mail_to
helperdef obfuscated_mail_to(email, options = {})
link_to obfuscate_email(email), "mail_to:#{email}", options
end
Testing that in the console:
obfuscated_mail_to "[email protected]", class: "email"
=> "<a class=\"email\" href=\"mail_to:[email protected]\">me_at_example_dot_com</a>"
Hope that helps!
Upvotes: 2