Afolabi Olaoluwa
Afolabi Olaoluwa

Reputation: 1948

How to make emails supplied in a Text Field formatted as an email link in Ruby on Rails

I have a text based form, which enables anyone to type a text and at the same time supply an email in it and submit the form. Upon submitting the form, its show action should look like this image:

enter image description here

The code works for web links but emails supplied in the text are not formatted as email links and comes out as ordinary text. when I check the source code from browser, I see no html tag was added to the email supplied and it rendered as a text.

How can I supply html tag to the emails supplied in this text field such that the preview shows a real email address?

form.html.erb

<%= simple_form_for @job do |f| %><br>
    <%= f.input :to_apply, label: 'How do people apply for this job?', placeholder: 'Example: Send a resume and cover letter to [email protected].' %><br>
<% end %>

model: job.rb

class Job < ActiveRecord::Base

  validates :to_apply,
            presence: true
end

Upvotes: 0

Views: 368

Answers (1)

SteveTurczyn
SteveTurczyn

Reputation: 36860

sanitize the text to remove any tags the user may have entered, scan for email addresses and replace with gsub and the mail_to helper, indicate the string is html_safe Build a helper method to do this...

class ApplicationController

  helper_method :mailify

  def mailify(text)
    new_text = text.to_s.dup.sanitize
    new_text.scan(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i).each do |email|
      new_text.sub!(email, view_context.mail_to(email))
    end
    new_text.html_safe
  end

end

In your views...

<%= mailify(@job.to_apply) %> 

Upvotes: 1

Related Questions