Technology and Software

Favicon on Rails

Did you ever wanted to generate a <link rel="shortcut icon" href="/favicon.ico" /> tag with an helper to take advange of Rails’asset hosts, that is <link rel="shortcut icon" href="http://static.yourserver.com/favicon.ico" /> ? You’re only three easy steps away from it.

1. Add this code to lib/asset_tag_helper_ext.rb

module ActionView
  module Helpers
    module AssetTagHelper
      def link_tag(url_options = {}, tag_options = {})
        href = url_options.is_a?(Hash) ?
          url_for(url_options.merge(
            :only_path => false)) : url_options
        tag(
          "link",
          "rel"   => tag_options[:rel] || nil,
          "type"  => tag_options[:type] || nil,
          "title" => tag_options[:title] || nil,
          "href"  => compute_public_path(href, "", "")
        )
      end
    end
  end
end

2. Require it at the end of config/environment.rb as

require "asset_tag_helper_ext"

3. Add <%= link_tag("/favicon.ico", :rel => "shortcut icon") %> to your layout. Done!

This code has been tested with Rails 2.0.2 and Rails 2.3.2.

Standard