2017-01-13 11:24:41 +09:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2017-01-13 10:42:22 +09:00
|
|
|
module Settings
|
2017-05-25 12:18:08 +09:00
|
|
|
class ScopedSettings
|
2018-08-23 21:17:35 +09:00
|
|
|
DEFAULTING_TO_UNSCOPED = %w(
|
|
|
|
theme
|
2019-09-11 15:44:58 +09:00
|
|
|
noindex
|
2018-08-23 21:17:35 +09:00
|
|
|
).freeze
|
|
|
|
|
2017-05-25 12:18:08 +09:00
|
|
|
def initialize(object)
|
2017-01-13 10:42:22 +09:00
|
|
|
@object = object
|
|
|
|
end
|
|
|
|
|
2017-05-25 12:18:08 +09:00
|
|
|
def method_missing(method, *args)
|
|
|
|
method_name = method.to_s
|
|
|
|
# set a value for a variable
|
|
|
|
if method_name[-1] == '='
|
|
|
|
var_name = method_name.sub('=', '')
|
|
|
|
value = args.first
|
|
|
|
self[var_name] = value
|
|
|
|
else
|
|
|
|
# retrieve a value
|
|
|
|
self[method_name]
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2017-05-25 21:14:36 +09:00
|
|
|
def respond_to_missing?(*)
|
2017-05-25 12:18:08 +09:00
|
|
|
true
|
|
|
|
end
|
|
|
|
|
|
|
|
def all_as_records
|
|
|
|
vars = thing_scoped
|
2021-01-12 17:27:38 +09:00
|
|
|
records = vars.index_by(&:var)
|
2017-05-25 12:18:08 +09:00
|
|
|
|
2017-05-25 21:14:36 +09:00
|
|
|
Setting.default_settings.each do |key, default_value|
|
2017-05-25 12:18:08 +09:00
|
|
|
next if records.key?(key) || default_value.is_a?(Hash)
|
2023-02-20 14:58:28 +09:00
|
|
|
|
2017-05-25 12:18:08 +09:00
|
|
|
records[key] = Setting.new(var: key, value: default_value)
|
|
|
|
end
|
|
|
|
|
|
|
|
records
|
|
|
|
end
|
|
|
|
|
|
|
|
def []=(key, value)
|
|
|
|
key = key.to_s
|
2017-05-25 21:14:36 +09:00
|
|
|
record = thing_scoped.find_or_initialize_by(var: key)
|
|
|
|
record.update!(value: value)
|
2017-05-25 12:18:08 +09:00
|
|
|
|
|
|
|
Rails.cache.write(Setting.cache_key(key, @object), value)
|
|
|
|
end
|
|
|
|
|
|
|
|
def [](key)
|
|
|
|
Rails.cache.fetch(Setting.cache_key(key, @object)) do
|
|
|
|
db_val = thing_scoped.find_by(var: key.to_s)
|
|
|
|
if db_val
|
2018-08-23 21:17:35 +09:00
|
|
|
default_value = ScopedSettings.default_settings[key]
|
2017-05-25 12:18:08 +09:00
|
|
|
return default_value.with_indifferent_access.merge!(db_val.value) if default_value.is_a?(Hash)
|
2023-02-20 14:58:28 +09:00
|
|
|
|
2017-05-25 12:18:08 +09:00
|
|
|
db_val.value
|
|
|
|
else
|
2018-08-23 21:17:35 +09:00
|
|
|
ScopedSettings.default_settings[key]
|
2017-05-25 12:18:08 +09:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2018-08-23 21:17:35 +09:00
|
|
|
class << self
|
|
|
|
def default_settings
|
2021-03-24 18:44:31 +09:00
|
|
|
defaulting = DEFAULTING_TO_UNSCOPED.index_with { |k| Setting[k] }
|
2018-08-23 21:17:35 +09:00
|
|
|
Setting.default_settings.merge!(defaulting)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2017-05-25 12:18:08 +09:00
|
|
|
protected
|
|
|
|
|
|
|
|
def thing_scoped
|
|
|
|
Setting.unscoped.where(thing_type: @object.class.base_class.to_s, thing_id: @object.id)
|
2017-01-13 10:42:22 +09:00
|
|
|
end
|
|
|
|
end
|
2017-01-13 11:24:41 +09:00
|
|
|
end
|