public Method

TextHelper.auto_link(text, link = :all, href_options = {}, &block)

Turns all URLs and e-mail addresses into clickable links. The link parameter will limit what should be linked. You can add HTML attributes to the links using href_options. Options for link are :all (default), :email_addresses, and :urls. If a block is given, each URL and e-mail address is yielded and the result is used as the link text.

Examples

auto_link("Go to http://www.rubyonrails.org and say hello to david@loudthinking.com")
# => "Go to <a href="\"http://www.rubyonrails.org\">http://www.rubyonrails.org</a> and
#     say hello to <a href="\"mailto:david@loudthinking.com\">david@loudthinking.com</a>"

auto_link("Visit http://www.loudthinking.com/ or e-mail david@loudthinking.com", :urls)
# => "Visit <a href="\"http://www.loudthinking.com/\">http://www.loudthinking.com/</a>
#     or e-mail david@loudthinking.com"

auto_link("Visit http://www.loudthinking.com/ or e-mail david@loudthinking.com", :email_addresses)
# => "Visit http://www.loudthinking.com/ or e-mail <a href="\"mailto:david@loudthinking.com\">david@loudthinking.com</a>"

post_body = "Welcome to my new blog at http://www.myblog.com/.  Please e-mail me at me@email.com."
auto_link(post_body, :all, :target => '_blank') do |text|
  truncate(text, 15)
end
# => "Welcome to my new blog at <a href="\"http://www.myblog.com/\" target="\"_blank\">http://www.m...</a>.
      Please e-mail me at <a href="\"mailto:me@email.com\">me@email.com</a>."

Source Code

# File action_view/helpers/text_helper.rb, line 339
def auto_link(text, link = :all, href_options = {}, &block)
  return '' if text.blank?
  case link
    when :all             then auto_link_email_addresses(auto_link_urls(text, href_options, &block), &block)
    when :email_addresses then auto_link_email_addresses(text, &block)
    when :urls            then auto_link_urls(text, href_options, &block)
  end
end
Comments

Have your say
Please use Textile formatting (click here for a cheat sheet). Use <code/> and <pre/> for code samples.
Click here to login with OpenID to to post comments.