Last Updated: February 25, 2016
·
685
· cizambra

Simple google font helper for Rails 4

This font tag helper is made for an easy handle of the link tags that contains google fonts.

It accepts the following formats:

<%= font_tag(:open_sans, 400, 300) %>
<%= font_tag([:open_sans, 400, 300], [:lato, 400, 300]) %>
<%= font_tag({ name: :open_sans, sizes: [400, 300] }, { name: :lato, sizes: [400, 300]}) %>
def font_tag(fontname_hash_or_array, *args)
    #
    # The message error.
    #
    message  = 'The font_tag() helper receives a single font definition in the format :fontname, size1, size2, '
    message += 'a multiple font definition in an array format [:fontname1, size1, size2], [:fontname2, size1, size2], '
    message += 'or a multiple font definition in the hash format {name: :fontname1, sizes: [size1, size2]},{name: :fontname2, sizes: [size1, size2]}'

    case fontname_hash_or_array
      when Symbol , String
        fontname = fontname_hash_or_array
        #
        # If the `fontname_hash_or_array` param is a symbol, then it's converted and processed as a string.
        #
        fontname = fontname.to_s.humanize.titleize if fontname.class == Symbol
        fontname = fontname.split(/ /).join('+')
        #
        # For a better understanding of the context
        #
        sizes = args
        size_definition = (sizes and !sizes.empty?) ? ":#{sizes.join(',')}" : nil
        raw "<link href='http://fonts.googleapis.com/css?family=#{fontname}#{size_definition}' rel='stylesheet' type='text/css'/>"
      when Hash
        first_hash = fontname_hash_or_array 
        tag = font_tag first_hash[:name], first_hash[:sizes]
        #
        # For a better understanding of the context
        #
        hashes = args
        unless (!hashes || hashes.empty?)
          hashes.each do |hash|
            raise message unless hash.class == Hash
            tag += "\n"
            tag += font_tag hash[:name], hash[:sizes]
          end
        end
        tag
      when Array
        first_array = fontname_hash_or_array 
        tag = font_tag first_array.shift, first_array
        #
        # For a better understanding of the context
        #
        arrays = args
        unless (!arrays || arrays.empty?)
          arrays.each do |array|
            raise message unless array.class == Array
            tag += "\n"
            tag += font_tag array.shift, array
          end
        end
        tag
      else
        raise message
    end
  end