Method: StringAwesome::AwesomeMethods#linkify

Defined in:
lib/string_awesome/awesome_methods.rb

#linkify(options = {}) ⇒ Object

Finds URLs in text and wrap in anchor tag.

Example:

>> 'Awesome site: http://foobar.com'.linkify
=> 'Awesome site: <a href="http://foobar.com">http://foobar.com</a>'
>> 'Awesome site: http://foobar.com'.linkify(class: 'link', truncate: 10)
=> 'Awesome site: <a href="http://foobar.com" class="link">http://foo...</a>'

Arguments:

options: (Hash)
 - Options for the link tag, such as: 
   - :truncate - If set, it will truncate the URL displayed in the anchor tag 
                 and put an ellipsis according to the given length. It can
                 be also a Hash of options:
     - :length - URLs new length.
     - :html_encoded - Ellipsis will be displayed as HTML encoded char.
   - :class - Value for "class" attribute: <a href="url" class="link">url</a>
   - :target - Value for "target" attribute: <a href="url" target="_blank">url</a>


216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
# File 'lib/string_awesome/awesome_methods.rb', line 216

def linkify(options = {})
  self.gsub!(SA_REGEXES[:url]) do |match|
    # http://verylongurl...
    displayed = truncate_url match, options[:truncate]
    
    # Now that we're done with the 'truncate' option, let's remove it...
    options.delete(:truncate) unless !options
    
    # Forces the presence of the 'http://'
    match = "http://#{match}" unless match =~ SA_REGEXES[:protocol]
    
    "<a href=\"#{match}\"#{apply_tag_attrs(options)}>#{displayed}</a>"
  end
  self 
end