Linkificator

Changes link depending on context

Installation

Add this line to your application's Gemfile:

gem 'linkificator'

And then execute:

$ bundle

Or install it yourself as:

$ gem install linkificator

Options

Full list of options:

{
    context:    {
        target:      %w(http://example.com.*),   # href url
        target_not:  %w(http://example.com/a.*),
        current:     %w(http://example.dev.*),   # Rely on context[:current] field in you app.
                                                 # Usually current request url.
        current_not: %w(http://example.dev),
    },
    processing: {
        wrap_noindex: true # Wrap with <noindex> tag
        data_href:    true # Clear href and put it in base64 to data-href attribute
        rel_nofollow: true # Adds rel="nofollow" attribute to link tag
    }
}

Example

Lets wrap links to example.com with <noindex> tag:

Add to your application_controller.rb linkificator preferences:

class ApplicationController < ActionController::Base

  helper_method :linkificator

  def linkificator
    require 'linkificator'
    @linkificator ||= Linkificator.for_conditions([
      {
          context:    {target: %w(http://example.com.*)},
          processing: {wrap_noindex: true}
      }
    ])
  end
end

Now you can define seo_link_to helper in application_helper.rb:

module ApplicationHelper

  def seo_link_to(*params, &block)
    linkificator.link_to(
        *params[0, 1],
        (params[2] || {}).merge(
            view_context: self,
            context: {
                current: request.original_url
            }
        ),
        &block
    )
  end
end

Finally use new helper seo_link_to like default link_to

seo_link_to('text', 'http://example.com') # => <noindex><a href="http://example.com">text</a></noindex>
seo_link_to('text', 'http://other.com')   # => <a href="http://other.com">text</a>

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request