discourse/app/models/javascript_cache.rb
David Taylor f4b70c746d
DEV: Extract theme script tags into their own JS files (#33647)
Previously, all script tags in a theme field would be combined into a
single `.js` bundle along with the `text/discourse-plugin` modules. This
led to some unexpected run order, and also makes it hard to implement
the `type=module` change being developed in #33103.

This commit refactors things so that each raw script gets extracted into
its own `.js` bundle, which is then placed in exactly the same place in
the HTML.
2025-07-16 17:17:36 +01:00

60 lines
1.5 KiB
Ruby
Vendored

# frozen_string_literal: true
class JavascriptCache < ActiveRecord::Base
belongs_to :theme_field
belongs_to :theme
validate :content_cannot_be_nil
before_save :update_digest
def url
"#{GlobalSetting.cdn_url}#{Discourse.base_path}#{path}"
end
def local_url
"#{Discourse.base_path}#{path}"
end
private
def path
"/theme-javascripts/#{digest}.js?__ws=#{Discourse.current_hostname}"
end
def update_digest
self.digest =
Digest::SHA1.hexdigest(
"#{content}|#{source_map}|#{GlobalSetting.asset_url_salt}",
) if content_changed? || source_map_changed?
end
def content_cannot_be_nil
errors.add(:content, :empty) if content.nil?
end
end
# == Schema Information
#
# Table name: javascript_caches
#
# id :bigint not null, primary key
# theme_field_id :bigint
# digest :string
# content :text not null
# created_at :datetime not null
# updated_at :datetime not null
# theme_id :bigint
# source_map :text
# name :string
#
# Indexes
#
# index_javascript_caches_on_digest (digest)
# index_javascript_caches_on_theme_field_id_and_name (theme_field_id,name) UNIQUE WHERE (theme_field_id IS NOT NULL)
# index_javascript_caches_on_theme_id (theme_id) UNIQUE
#
# Foreign Keys
#
# fk_rails_... (theme_field_id => theme_fields.id) ON DELETE => cascade
# fk_rails_... (theme_id => themes.id) ON DELETE => cascade
#