Lucky - Fathom Analytics

Integrate Fathom Analytics into a Lucky Application
Icons/chart bar
Used 21 times
Created by
S Stephen Dolan

Usage
From within a Lucky application with the bloat gem installed, run:
bloat with https://railsbytes.com/script/V1bsQQ

Run this command in your Rails app directory in the terminal:

rails app:template LOCATION="https://railsbytes.com/script/V1bsQQ"
Template Source

Review the code before running this template on your machine.

def create_config_file(domain:)
  create_file "config/fathom.cr" do
    <<~EOF
    class Fathom
      Habitat.create do
        setting domain : String
        setting site_id : String
      end
    end

    Fathom.configure do |settings|
      settings.domain = "#{domain}"
      settings.site_id = fathom_site_id_from_env
    end

    # Only require this ENV var in production.
    private def fathom_site_id_from_env
      return "UNUSED" unless Lucky::Env.production?

      ENV["FATHOM_SITE_ID"]? || raise_missing_key_message
    end

    private def raise_missing_key_message
      puts "Missing FATHOM_SITE_ID. Set the FATHOM_SITE_ID env variable to 'unused' if not tracking errors, or set the FATHOM_SITE_ID ENV var.".colorize.red
      exit(1)
    end
    EOF
  end
end

def inject_fathom_analytics
  inject_into_file "src/components/shared/layout_head.cr", after: "head do\n" do
    <<-EOF
      if Lucky::Env.production?
        script src: "https://\#{Fathom.settings.domain}/script.js", data_site: Fathom.settings.site_id, attrs: [:defer]
      end
      
    EOF
  end
end

domain = ask "What is your Fathom domain (only necessary with custom domains)?", default: "cdn.usefathom.com"

# Create the configuration file
create_config_file(domain: domain)

# Inject Fathom script into layout file
inject_fathom_analytics
Comments

Sign up or Login to leave a comment.