method

auto_link

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

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 [email protected]")
  # => "Go to <a href=\"http://www.rubyonrails.org\">http://www.rubyonrails.org</a> and
  #     say hello to <a href=\"mailto:[email protected]\">[email protected]</a>"

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

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

  post_body = "Welcome to my new blog at http://www.myblog.com/.  Please e-mail me at [email protected]."
  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:[email protected]\">[email protected]</a>."

1Note

Documentation bug

jneto ยท Aug 6, 20094 thanks

When adding the :target option, the documentation states that you should user :href_options like so:

auto_link(post_body, :href_options => { :target => '_blank' })

However, I could only get it to work using :html instead:

auto_link(post_body, :html => { :target => '_blank' })

I'm using Rails 2.2.2, but I believe that this also happens for more recent version .