mirror of
https://github.com/discourse/discourse.git
synced 2024-11-26 18:03:38 +08:00
PERF: omit 2 queries on every full page load
This commit is contained in:
parent
59b5670e9c
commit
3853e3cfdc
|
@ -1,7 +1,12 @@
|
|||
require_dependency 'sass/discourse_stylesheets'
|
||||
require_dependency 'distributed_cache'
|
||||
|
||||
class ColorScheme < ActiveRecord::Base
|
||||
|
||||
def self.hex_cache
|
||||
@hex_cache ||= DistributedCache.new("scheme_hex_for_name")
|
||||
end
|
||||
|
||||
attr_accessor :is_base
|
||||
|
||||
has_many :color_scheme_colors, -> { order('id ASC') }, dependent: :destroy
|
||||
|
@ -12,6 +17,8 @@ class ColorScheme < ActiveRecord::Base
|
|||
|
||||
after_destroy :destroy_versions
|
||||
after_save :publish_discourse_stylesheet
|
||||
after_save :dump_hex_cache
|
||||
after_destroy :dump_hex_cache
|
||||
|
||||
validates_associated :color_scheme_colors
|
||||
|
||||
|
@ -64,8 +71,14 @@ class ColorScheme < ActiveRecord::Base
|
|||
end
|
||||
|
||||
def self.hex_for_name(name)
|
||||
val = begin
|
||||
hex_cache[name] ||= begin
|
||||
# Can't use `where` here because base doesn't allow it
|
||||
(enabled || base).colors.find {|c| c.name == name }.try(:hex)
|
||||
(enabled || base).colors.find {|c| c.name == name }.try(:hex) || :nil
|
||||
end
|
||||
end
|
||||
|
||||
val == :nil ? nil : val
|
||||
end
|
||||
|
||||
def colors=(arr)
|
||||
|
@ -101,6 +114,11 @@ class ColorScheme < ActiveRecord::Base
|
|||
DiscourseStylesheets.cache.clear
|
||||
end
|
||||
|
||||
|
||||
def dump_hex_cache
|
||||
self.class.hex_cache.clear
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
# == Schema Information
|
||||
|
|
|
@ -42,6 +42,10 @@ describe ColorScheme do
|
|||
end
|
||||
|
||||
context "hex_for_name without anything enabled" do
|
||||
before do
|
||||
ColorScheme.hex_cache.clear
|
||||
end
|
||||
|
||||
it "returns nil for a missing attribute" do
|
||||
expect(described_class.hex_for_name('undefined')).to eq nil
|
||||
end
|
||||
|
@ -55,8 +59,8 @@ describe ColorScheme do
|
|||
describe "destroy" do
|
||||
it "also destroys old versions" do
|
||||
c1 = described_class.create(valid_params.merge(version: 2))
|
||||
c2 = described_class.create(valid_params.merge(versioned_id: c1.id, version: 1))
|
||||
other = described_class.create(valid_params)
|
||||
_c2 = described_class.create(valid_params.merge(versioned_id: c1.id, version: 1))
|
||||
_other = described_class.create(valid_params)
|
||||
expect {
|
||||
c1.destroy
|
||||
}.to change { described_class.count }.by(-2)
|
||||
|
@ -69,6 +73,7 @@ describe ColorScheme do
|
|||
end
|
||||
|
||||
it "returns the enabled color scheme" do
|
||||
ColorScheme.hex_cache.clear
|
||||
expect(described_class.hex_for_name('$primary_background_color')).to eq nil
|
||||
c = described_class.create(valid_params.merge(enabled: true))
|
||||
expect(described_class.enabled.id).to eq c.id
|
||||
|
|
Loading…
Reference in New Issue
Block a user