2019-05-02 18:17:27 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2018-03-04 19:04:23 -05:00
|
|
|
class ThemeSetting < ActiveRecord::Base
|
|
|
|
belongs_to :theme
|
|
|
|
|
2022-06-08 19:24:30 -04:00
|
|
|
has_many :upload_references, as: :target, dependent: :destroy
|
|
|
|
|
2018-03-04 19:04:23 -05:00
|
|
|
validates_presence_of :name, :theme
|
|
|
|
validates :data_type, numericality: { only_integer: true }
|
|
|
|
validates :name, length: { maximum: 255 }
|
|
|
|
|
2019-04-12 06:36:08 -04:00
|
|
|
after_save :clear_settings_cache
|
|
|
|
after_destroy :clear_settings_cache
|
|
|
|
|
2022-06-08 19:24:30 -04:00
|
|
|
after_save do
|
|
|
|
if self.data_type == ThemeSetting.types[:upload] && saved_change_to_value?
|
|
|
|
UploadReference.ensure_exist!(upload_ids: [self.value], target: self)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2019-04-12 06:36:08 -04:00
|
|
|
def clear_settings_cache
|
|
|
|
# All necessary caches will be cleared on next ensure_baked!
|
|
|
|
theme.settings_field&.invalidate_baked!
|
2018-03-04 19:04:23 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def self.types
|
2020-04-15 09:04:02 -04:00
|
|
|
@types ||= Enum.new(integer: 0, float: 1, string: 2, bool: 3, list: 4, enum: 5, upload: 6)
|
2018-03-04 19:04:23 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def self.acceptable_value_for_type?(value, type)
|
|
|
|
case type
|
|
|
|
when self.types[:integer]
|
|
|
|
value.is_a?(Integer)
|
|
|
|
when self.types[:float]
|
|
|
|
value.is_a?(Integer) || value.is_a?(Float)
|
|
|
|
when self.types[:bool]
|
|
|
|
value.is_a?(TrueClass) || value.is_a?(FalseClass)
|
|
|
|
when self.types[:list]
|
|
|
|
value.is_a?(String)
|
|
|
|
else
|
|
|
|
true
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.value_in_range?(value, range, type)
|
|
|
|
if type == self.types[:integer] || type == self.types[:float]
|
|
|
|
range.include? value
|
|
|
|
elsif type == self.types[:string]
|
|
|
|
range.include? value.to_s.length
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.guess_type(value)
|
|
|
|
case value
|
|
|
|
when Integer
|
|
|
|
types[:integer]
|
|
|
|
when Float
|
|
|
|
types[:float]
|
|
|
|
when String
|
|
|
|
types[:string]
|
|
|
|
when TrueClass, FalseClass
|
|
|
|
types[:bool]
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
# == Schema Information
|
|
|
|
#
|
|
|
|
# Table name: theme_settings
|
|
|
|
#
|
2019-05-02 18:34:12 -04:00
|
|
|
# id :bigint not null, primary key
|
2018-03-04 19:04:23 -05:00
|
|
|
# name :string(255) not null
|
|
|
|
# data_type :integer not null
|
2018-03-04 19:06:45 -05:00
|
|
|
# value :text
|
2018-03-04 19:04:23 -05:00
|
|
|
# theme_id :integer not null
|
|
|
|
# created_at :datetime not null
|
|
|
|
# updated_at :datetime not null
|
|
|
|
#
|