Skip to content

Hreflang Tag Generator — Ruby source

Turn a list of language versions into a valid hreflang set — locale normalization, duplicate detection and x-default handling — emitted as HTML link tags or an XML sitemap block.

This is the Ruby implementation — the same logic the interactive tool runs, in a shareable, citable form.

# frozen_string_literal: true

# hreflang-tag-generator — pure locale-list validation + alternate-link
# emission (SEO/meta trio). Authored snippet mirroring src/lib/hreflang.ts:
# normalize_locale + build_hreflang are a pure port of the TS grammar — the
# ll/ll-CC case-correcting locale rules, the row-located error strings,
# x-default appended last, and both output flavors (HTML <link> block and
# XML sitemap <xhtml:link> block, indentation and self-closing style
# included). Standard library only.

module HreflangTagGenerator
  # One locale/URL pair. Mirrors the TS HreflangRow interface.
  Row = Struct.new(:locale, :url)

  # The field set for build_hreflang — rows plus an optional x-default URL.
  Input = Struct.new(:rows, :x_default_url) do
    def initialize(rows: [], x_default_url: nil)
      super
    end
  end

  # Diagnostics plus both emitted flavors. On failure ok is false, errors
  # lists every row-located problem, and normalized/html/sitemap are empty —
  # exactly like the TS result.
  Result = Struct.new(:ok, :errors, :normalized, :html, :sitemap)

  # Normalize a locale tag to Google's hreflang grammar: `ll` (ISO-639-1,
  # lowercase) or `ll-CC` (region uppercase, ISO-3166). Case and surrounding
  # whitespace are corrected (`en-us` -> `en-US`); anything else is invalid
  # and returns nil. The Ruby twin of normalizeLocale() in
  # src/lib/hreflang.ts — nil stands in for the TS null.
  SINGLE_RE = /\A([a-zA-Z]{2})\z/.freeze
  REGION_RE = /\A([a-zA-Z]{2})-([a-zA-Z]{2})\z/.freeze
  URL_RE = /\Ahttps?:\/\//.freeze

  module_function

  def normalize_locale(raw)
    t = (raw || '').to_s.strip
    if (m = SINGLE_RE.match(t))
      return m[1].downcase
    end
    if (m = REGION_RE.match(t))
      return "#{m[1].downcase}-#{m[2].upcase}"
    end
    nil
  end

  # Trim raw and return it when it starts with http:// or https://, otherwise
  # nil. Mirrors the TS validUrl() helper.
  def valid_url(raw)
    t = raw.to_s.strip
    URL_RE.match?(t) ? t : nil
  end

  # Validate a locale/URL table and emit both hreflang flavors. Invalid input
  # collects every error (row-located) and emits empty blocks; valid input
  # normalizes locales, preserves row order, and appends x-default last.
  def build_hreflang(input)
    errors = []
    normalized = []
    seen = {}

    (input.rows || []).each_with_index do |row, i|
      n = i + 1
      raw_locale = row.locale || ''
      locale = normalize_locale(raw_locale)
      if locale.nil?
        errors << %(Row #{n}: "#{raw_locale.strip}" is not a valid locale — use ll or ll-CC (e.g. en, de-AT).)
        next
      end
      if seen.key?(locale)
        errors << %(Row #{n}: locale "#{locale}" is already used.)
        next
      end
      if row.url.nil? || row.url.to_s.strip.empty?
        errors << "Row #{n}: URL is required."
        next
      end
      url = valid_url(row.url)
      if url.nil?
        errors << "Row #{n}: URL must start with http:// or https://."
        next
      end
      seen[locale] = true
      normalized << Row.new(locale, url)
    end

    x_default = nil
    xd = input.x_default_url
    if !xd.nil? && !xd.to_s.strip.empty?
      x_default = valid_url(xd)
      errors << 'x-default: URL must start with http:// or https://.' if x_default.nil?
    end

    if errors.any?
      return Result.new(false, errors, [], '', '')
    end

    html_lines = normalized.map do |r|
      %(<link rel="alternate" href="#{r.url}" hreflang="#{r.locale}" />)
    end
    sitemap_lines = normalized.map do |r|
      %(    <xhtml:link rel="alternate" hreflang="#{r.locale}" href="#{r.url}"/>)
    end
    unless x_default.nil?
      html_lines << %(<link rel="alternate" href="#{x_default}" hreflang="x-default" />)
      sitemap_lines << %(    <xhtml:link rel="alternate" hreflang="x-default" href="#{x_default}"/>)
    end

    Result.new(true, [], normalized, html_lines.join("\n"), sitemap_lines.join("\n"))
  end
end

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →