DEV Community

SunnahSource
SunnahSource

Posted on

Build a Quran Study Sheet Generator in Ruby (stdlib only): Tafseer + Word by Word JSON, ETag cache, RTL HTML

Ruby ships with everything you need to talk to a JSON API: net/http, json, optparse, fileutils and cgi. No Bundler, no gems. In this tutorial we use only the standard library to build a small Quran study sheet generator that combines two public JSON samples from SunnahSource, an Islamic API for developers:

  • Tafseer API: https://sunnahsource.org/data/json/tafseer.json (commentary per ayah, 9 languages)
  • Word by Word Quran API: https://sunnahsource.org/data/json/word-by-word-quran.json (each Arabic word with transliteration, root, grammar and meaning)

The tool will:

  1. Download both files with a real HTTP cache (ETag + If-None-Match, so repeat runs get a 304 Not Modified).
  2. Join them on the ayah number, even though the word-by-word file uses two different word shapes.
  3. Pick a language (en, ur, fr, de, tr, ms, ru, zh-CN, ja) and fall back to English when a field is missing.
  4. Print a terminal study sheet and optionally write an escaped, right-to-left-aware HTML page.
  5. Work offline from the cache.

Tested with Ruby 3.3.

1. Look at the data first

Always read the payload before writing code:

curl -s https://sunnahsource.org/data/json/tafseer.json | ruby -rjson -e 'd = JSON.parse(STDIN.read); p d.keys; p d["surah"]; p d["items"][0].keys; p d["items"][0]["translations"].keys'
Enter fullscreen mode Exit fullscreen mode
["title", "description", "is_free", "surah", "items"]
{"number"=>1, "name"=>"Al-Fatiha", "arabic"=>"الفاتحة"}
["ayah", "arabic", "translations"]
["en", "ur", "fr", "de", "tr", "ms", "ru", "zh-CN", "ja"]
Enter fullscreen mode Exit fullscreen mode

The word-by-word file is more interesting. Ayah 1 lives in a top-level words array with rich fields:

{ "position": 1, "arabic": "...", "transliteration": "Bismi", "root": "...",
  "grammar": "Preposition + Noun",
  "translations": { "en": "In the name of", "ur": "...", "fr": "...", "de": "...", "tr": "...", "ms": "..." } }
Enter fullscreen mode Exit fullscreen mode

while the next ayah sits in items[].words with a flatter shape:

{ "arabic": "...", "meaning_en": "All praise", "meaning_ur": "..." }
Enter fullscreen mode Exit fullscreen mode

Real data is like this. Instead of fighting it in the view code, we normalize both shapes into one Word struct.

2. The code: study_sheet.rb

One file, no dependencies:

#!/usr/bin/env ruby
# frozen_string_literal: true
# Quran study sheet: SunnahSource Tafseer API + Word by Word Quran API
# Ruby stdlib only (net/http, json, optparse, fileutils, cgi).

require "net/http"
require "json"
require "optparse"
require "fileutils"
require "cgi"

module StudySheet
  BASE = "https://sunnahsource.org/data/json"
  CACHE_DIR = File.join(Dir.home, ".cache", "sunnahsource")
  FALLBACK = "en"

  Word = Struct.new(:position, :arabic, :transliteration, :root, :grammar, :meaning, keyword_init: true)
  Ayah = Struct.new(:surah, :ayah, :arabic, :tafseer, :words, keyword_init: true)

  class Error < StandardError; end

  # GET with an ETag cache: send If-None-Match, reuse the body on 304.
  def self.fetch_json(name, offline: false)
    FileUtils.mkdir_p(CACHE_DIR)
    body_path = File.join(CACHE_DIR, "#{name}.json")
    etag_path = "#{body_path}.etag"

    if offline
      raise Error, "no cached copy of #{name}.json (run once online)" unless File.exist?(body_path)
      return [JSON.parse(File.read(body_path)), :offline]
    end

    uri = URI("#{BASE}/#{name}.json")
    req = Net::HTTP::Get.new(uri)
    req["Accept"] = "application/json"
    req["User-Agent"] = "study-sheet-ruby/1.0"
    req["If-None-Match"] = File.read(etag_path).strip if File.exist?(etag_path) && File.exist?(body_path)

    res = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 10, read_timeout: 20) do |http|
      http.request(req)
    end

    case res
    when Net::HTTPNotModified
      [JSON.parse(File.read(body_path)), :not_modified]
    when Net::HTTPSuccess
      body = res.body.force_encoding("UTF-8")
      data = JSON.parse(body) # validate before caching
      File.write(body_path, body)
      File.write(etag_path, res["ETag"]) if res["ETag"]
      [data, :fresh]
    else
      raise Error, "#{uri} returned HTTP #{res.code}"
    end
  rescue SocketError, Net::OpenTimeout, Net::ReadTimeout, Errno::ECONNREFUSED => e
    raise Error, "network error (#{e.class}); try --offline" unless File.exist?(body_path)
    warn "network error, using cached #{name}.json"
    [JSON.parse(File.read(body_path)), :stale]
  end

  # Pick a language, falling back to English when a translation is missing.
  def self.pick(translations, lang)
    return nil unless translations.is_a?(Hash)
    translations[lang] || translations[FALLBACK]
  end

  # word-by-word-quran.json has two word shapes:
  #   top-level "words": {position, arabic, transliteration, root, grammar, translations{...}}
  #   items[].words:     {arabic, meaning_en, meaning_ur}
  def self.normalize_word(raw, index, lang)
    meaning = pick(raw["translations"], lang) || raw["meaning_#{lang}"] || raw["meaning_#{FALLBACK}"]
    Word.new(
      position: raw["position"] || index + 1,
      arabic: raw["arabic"],
      transliteration: raw["transliteration"],
      root: raw["root"],
      grammar: raw["grammar"],
      meaning: meaning
    )
  end

  def self.word_map(wbw, lang)
    map = {}
    if wbw["words"]
      map[wbw["ayah"]] = wbw["words"].each_with_index.map { |w, i| normalize_word(w, i, lang) }
    end
    Array(wbw["items"]).each do |item|
      map[item["ayah"]] = item["words"].each_with_index.map { |w, i| normalize_word(w, i, lang) }
    end
    map
  end

  # Join tafseer items with word-by-word data on the ayah number.
  def self.build(tafseer, wbw, lang)
    surah = tafseer.dig("surah", "number")
    words = word_map(wbw, lang)
    tafseer.fetch("items").map do |item|
      Ayah.new(
        surah: surah,
        ayah: item["ayah"],
        arabic: item["arabic"],
        tafseer: pick(item["translations"], lang),
        words: wbw["surah"] == surah ? words.fetch(item["ayah"], []) : []
      )
    end
  end

  def self.to_text(ayahs, surah_name)
    ayahs.map do |a|
      lines = ["#{surah_name} #{a.surah}:#{a.ayah}", "  #{a.arabic}"]
      a.words.each do |w|
        extra = [w.transliteration, w.root && "root #{w.root}", w.grammar].compact.join(" | ")
        lines << format("  %2d. %s  %s%s", w.position, w.arabic, w.meaning, extra.empty? ? "" : "  (#{extra})")
      end
      lines << "  Tafseer: #{a.tafseer}"
      lines.join("\n")
    end.join("\n\n")
  end

  def self.to_html(ayahs, surah_name, lang)
    h = ->(s) { CGI.escapeHTML(s.to_s) }
    rows = ayahs.map do |a|
      words = a.words.map do |w|
        "<li><span class=\"ar\" lang=\"ar\" dir=\"rtl\">#{h[w.arabic]}</span> " \
          "#{h[w.meaning]}#{w.transliteration ? " <small>#{h[w.transliteration]}</small>" : ''}</li>"
      end.join
      <<~HTML
        <section>
          <h2>#{h[surah_name]} #{a.surah}:#{a.ayah}</h2>
          <p class="ar" lang="ar" dir="rtl">#{h[a.arabic]}</p>
          #{words.empty? ? '' : "<ol class=\"words\">#{words}</ol>"}
          <p class="tafseer" lang="#{h[lang]}">#{h[a.tafseer]}</p>
        </section>
      HTML
    end.join
    <<~HTML
      <!doctype html>
      <html lang="#{h[lang]}"><head><meta charset="utf-8">
      <title>#{h[surah_name]} study sheet</title>
      <style>body{font-family:system-ui,sans-serif;max-width:720px;margin:2rem auto;padding:0 1rem}
      .ar{font-size:1.6rem;text-align:right}.words .ar{font-size:1.2rem}small{color:#666}</style>
      </head><body>
      <h1>#{h[surah_name]} study sheet</h1>
      #{rows}
      <p><small>Data: <a href="https://sunnahsource.org/apis/tafseer/">SunnahSource Tafseer API</a> and
      <a href="https://sunnahsource.org/apis/word-by-word-quran/">Word by Word Quran API</a>.</small></p>
      </body></html>
    HTML
  end

  def self.main(argv)
    opts = { lang: "en", ayah: nil, html: nil, offline: false }
    OptionParser.new do |o|
      o.banner = "Usage: study_sheet.rb [--lang ur] [--ayah 1] [--html out.html] [--offline]"
      o.on("--lang LANG", "en, ur, fr, de, tr, ms, ru, zh-CN, ja") { |v| opts[:lang] = v }
      o.on("--ayah N", Integer, "only this ayah") { |v| opts[:ayah] = v }
      o.on("--html FILE", "also write an HTML study sheet") { |v| opts[:html] = v }
      o.on("--offline", "use the cached JSON only") { opts[:offline] = true }
    end.parse!(argv)

    tafseer, s1 = fetch_json("tafseer", offline: opts[:offline])
    wbw, s2 = fetch_json("word-by-word-quran", offline: opts[:offline])
    warn "tafseer.json: #{s1}, word-by-word-quran.json: #{s2}"

    ayahs = build(tafseer, wbw, opts[:lang])
    ayahs.select! { |a| a.ayah == opts[:ayah] } if opts[:ayah]
    raise Error, "ayah #{opts[:ayah]} is not in the sample data" if ayahs.empty?

    name = tafseer.dig("surah", "name")
    puts to_text(ayahs, name)
    if opts[:html]
      File.write(opts[:html], to_html(ayahs, name, opts[:lang]))
      warn "wrote #{opts[:html]}"
    end
    0
  rescue Error, OptionParser::ParseError => e
    warn "error: #{e.message}"
    1
  end
end

exit(StudySheet.main(ARGV)) if $PROGRAM_NAME == __FILE__
Enter fullscreen mode Exit fullscreen mode

A few things worth pointing out:

  • Validate before caching. JSON.parse(body) runs before the file is written, so a broken response never poisons the cache.
  • Conditional GET. The stored ETag goes back as If-None-Match. The server answers 304 with no body, and we reuse the cached JSON.
  • Two shapes, one struct. normalize_word reads translations[lang] first, then meaning_<lang>, then the English versions. Missing position falls back to the array index.
  • Escaping. Everything goes through CGI.escapeHTML, and Arabic gets lang="ar" dir="rtl" so screen readers and browsers handle it properly.

3. Run it

First run downloads both files, the second gets 304 Not Modified:

ruby study_sheet.rb --ayah 1
Enter fullscreen mode Exit fullscreen mode
tafseer.json: fresh, word-by-word-quran.json: fresh
Al-Fatiha 1:1
  بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ
   1. بِسْمِ  In the name of  (Bismi | root س م و | Preposition + Noun)
   2. اللَّهِ  Allah  (Allah | root ا ل ه | Proper Noun (Genitive))
   3. الرَّحْمَٰنِ  The Most Gracious  (Ar-Rahman | root ر ح م | Adjective (Genitive))
   4. الرَّحِيمِ  The Especially Merciful  (Ar-Raheem | root ر ح م | Adjective (Genitive))
  Tafseer: Bismillah begins every surah except At-Tawbah. Ibn Kathir explains: we start with Allah's name seeking His blessings. Ar-Rahman is mercy for all creation in this world; Ar-Raheem is special mercy for believers in the Hereafter.
Enter fullscreen mode Exit fullscreen mode

(Arabic text, word meanings and commentary above are printed exactly as returned by the API for Surah Al-Fatiha 1:1.)

Ayah 2 uses the flatter word shape, and the output looks the same:

ruby study_sheet.rb --ayah 2
Enter fullscreen mode Exit fullscreen mode
tafseer.json: not_modified, word-by-word-quran.json: not_modified
Al-Fatiha 1:2
  الْحَمْدُ لِلَّهِ رَبِّ الْعَالَمِينَ
   1. الْحَمْدُ  All praise
   2. لِلَّهِ  for Allah
   3. رَبِّ  Lord
   4. الْعَالَمِينَ  of the worlds
  Tafseer: All praise belongs to Allah alone — for His creation, sustenance, and guidance. Rabb means Master, Owner, and Sustainer of all worlds (humans, jinn, angels, and all creation).
Enter fullscreen mode Exit fullscreen mode

Other options:

ruby study_sheet.rb --lang ur --html fatiha.html   # Urdu + HTML study sheet
ruby study_sheet.rb --lang ja --offline            # Japanese commentary, cached data only
ruby study_sheet.rb --ayah 7                       # "error: ayah 7 is not in the sample data", exit 1
Enter fullscreen mode Exit fullscreen mode

With --lang ja, the commentary comes back in Japanese. The word meanings fall back to English, because the word-by-word sample only has en, ur, fr, de, tr and ms. That is exactly why the fallback exists.

4. Tests with Minitest (also stdlib)

The join and fallback logic is pure, so it's easy to test without the network:

require "minitest/autorun"
require_relative "study_sheet"

class StudySheetTest < Minitest::Test
  TAFSEER = {
    "surah" => { "number" => 1, "name" => "Al-Fatiha" },
    "items" => [
      { "ayah" => 1, "arabic" => "A1", "translations" => { "en" => "t1 en", "ur" => "t1 ur" } },
      { "ayah" => 2, "arabic" => "A2", "translations" => { "en" => "t2 en" } }
    ]
  }.freeze
  WBW = {
    "surah" => 1, "ayah" => 1,
    "words" => [{ "position" => 1, "arabic" => "w1", "transliteration" => "Bismi", "root" => "r",
                  "grammar" => "g", "translations" => { "en" => "In the name of", "ur" => "u" } }],
    "items" => [{ "ayah" => 2, "words" => [{ "arabic" => "w2", "meaning_en" => "All praise", "meaning_ur" => "u2" }] }]
  }.freeze

  def test_joins_both_word_shapes
    a = StudySheet.build(TAFSEER, WBW, "en")
    assert_equal [1, 2], a.map(&:ayah)
    assert_equal "In the name of", a[0].words[0].meaning
    assert_equal "All praise", a[1].words[0].meaning
    assert_equal 1, a[1].words[0].position
  end

  def test_language_and_fallback
    a = StudySheet.build(TAFSEER, WBW, "ur")
    assert_equal "t1 ur", a[0].tafseer
    assert_equal "t2 en", a[1].tafseer # no ur -> en
    assert_equal "u2", a[1].words[0].meaning
    assert_equal "In the name of", StudySheet.build(TAFSEER, WBW, "ja")[0].words[0].meaning
  end

  def test_html_is_escaped_and_rtl
    a = StudySheet.build(TAFSEER.merge("items" => [{ "ayah" => 1, "arabic" => "<b>", "translations" => { "en" => "x&y" } }]), WBW, "en")
    html = StudySheet.to_html(a, "Al-Fatiha", "en")
    assert_includes html, "&lt;b&gt;"
    assert_includes html, "x&amp;y"
    assert_includes html, 'dir="rtl"'
  end
end
Enter fullscreen mode Exit fullscreen mode
ruby test_study_sheet.rb
# 3 runs, 14 assertions, 0 failures, 0 errors, 0 skips
Enter fullscreen mode Exit fullscreen mode

5. Ideas to extend it

  • Add a --format markdown option and paste study sheets into notes or a static site.
  • Wrap StudySheet.build in a tiny Sinatra or Rack endpoint and serve the HTML.
  • Add more datasets using the same fetch-validate-cache pattern: the Free Quran API (translations), the Quran Topics API or the Hadith API.

Notes

Top comments (0)