我想混淆我网页上的电子邮件地址。我希望避免js,以防我的用户停用它。
我发现了这个宝石:actionview-encoded_mail_to但似乎对我不起作用它在页面上显示完整的电子邮件地址(这很好),但它也在控制台中显示。
我试了三个例子,结果都一样。gem出现在我的gemfile中,因此应该正确安装。

最佳答案

你可以自己滚,但是,首先,那颗宝石肯定有用以下是我所做的…
使用宝石
我在rails 4.2应用程序中添加了gem:

# Gemfile
gem 'actionview-encoded_mail_to'

我安装了它:
$ bundle install

我进入控制台:
$ rails console

我在控制台中提供了helper方法:
include ActionView::Helpers::UrlHelper

使用与示例相同的参数调用了mail_to帮助程序:
mail_to "me@domain.com", nil, replace_at: "_at_", replace_dot: "_dot_", class: "email"

…结果是:
"<a class=\"email\" href=\"mailto:me@domain.com\">me_at_domain_dot_com</a>"

这看起来很模糊。你采取了什么措施?
把你自己弄糊涂了
这将是一个简单的字符串替换来混淆电子邮件字符串,我们可以使用"me_at_domain_dot_com"
def obfuscate_email(email, replace_at: '_at_', replace_dot: '_dot_')
  email.sub("@", replace_at).sub ".", replace_dot
end

我在控制台上测试过:
obfuscate_email "me@example.com"
# => "me_at_example_dot_com"

您可以将该方法放在sub中,并在任何视图中使用它:
link_to obfuscate_email(user.email), "mailto:#{user.email}"
# => "<a href=\"mailto:me@example.com\">me_at_example_dot_com</a>"

请注意,为了使其正常工作,href必须是未混淆的电子邮件。
走向更完整的帮手
def obfuscated_mail_to(email, options = {})
  link_to obfuscate_email(email), "mail_to:#{email}", options
end

在控制台中测试:
obfuscated_mail_to "me@example.com", class: "email"
=> "<a class=\"email\" href=\"mail_to:me@example.com\">me_at_example_dot_com</a>"

希望能有帮助!

10-06 12:42
查看更多