Skip to content

Instantly share code, notes, and snippets.

@juanjoseijas
Created January 21, 2018 19:53
Show Gist options
  • Save juanjoseijas/92ae78c8f46eeb336e43cc770e625619 to your computer and use it in GitHub Desktop.
Save juanjoseijas/92ae78c8f46eeb336e43cc770e625619 to your computer and use it in GitHub Desktop.
Google Fonts helper
def google_fonts(*query)
raise ArgumentError, 'Expected at least one font.' if query.empty?
if query.first.is_a? Hash
query = [*query.first].transpose
query = [query.first, query.last.to_enum]
end
api_base_url = 'http://fonts.googleapis.com/css'
# Iterate through given font families, building the query string from them and given styles
query_string = '?family=' + [*query.first].collect { |family|
# Stringify and title-case family name, replacing underscores with spaces
family_str = family.to_s.split(/ |_/).map(&:capitalize).join('+')
# Append any given styles to current font family string
if query[1]
# Using an Enumerator allows for mapping different styles to each font family
styles = query.last.is_a?(Enumerator) ? query.last.next : query.last
# [API] styles are enumerated after a colon, and delineated by a comma
family_str << ':' << [*styles].join(',')
end
family_str
}.join('|') # [API] families are separated by the pipe character
%Q[<link rel="stylesheet" type="text/css" href="#{api_base_url + query_string}" />]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment