You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
2.0 KiB

  1. # frozen_string_literal: true
  2. module Settings
  3. class ScopedSettings
  4. DEFAULTING_TO_UNSCOPED = %w(
  5. theme
  6. noindex
  7. ).freeze
  8. def initialize(object)
  9. @object = object
  10. end
  11. # rubocop:disable Style/MethodMissingSuper
  12. def method_missing(method, *args)
  13. method_name = method.to_s
  14. # set a value for a variable
  15. if method_name[-1] == '='
  16. var_name = method_name.sub('=', '')
  17. value = args.first
  18. self[var_name] = value
  19. else
  20. # retrieve a value
  21. self[method_name]
  22. end
  23. end
  24. # rubocop:enable Style/MethodMissingSuper
  25. def respond_to_missing?(*)
  26. true
  27. end
  28. def all_as_records
  29. vars = thing_scoped
  30. records = vars.each_with_object({}) { |r, h| h[r.var] = r }
  31. Setting.default_settings.each do |key, default_value|
  32. next if records.key?(key) || default_value.is_a?(Hash)
  33. records[key] = Setting.new(var: key, value: default_value)
  34. end
  35. records
  36. end
  37. def []=(key, value)
  38. key = key.to_s
  39. record = thing_scoped.find_or_initialize_by(var: key)
  40. record.update!(value: value)
  41. Rails.cache.write(Setting.cache_key(key, @object), value)
  42. end
  43. def [](key)
  44. Rails.cache.fetch(Setting.cache_key(key, @object)) do
  45. db_val = thing_scoped.find_by(var: key.to_s)
  46. if db_val
  47. default_value = ScopedSettings.default_settings[key]
  48. return default_value.with_indifferent_access.merge!(db_val.value) if default_value.is_a?(Hash)
  49. db_val.value
  50. else
  51. ScopedSettings.default_settings[key]
  52. end
  53. end
  54. end
  55. class << self
  56. def default_settings
  57. defaulting = DEFAULTING_TO_UNSCOPED.each_with_object({}) { |k, h| h[k] = Setting[k] }
  58. Setting.default_settings.merge!(defaulting)
  59. end
  60. end
  61. protected
  62. def thing_scoped
  63. Setting.unscoped.where(thing_type: @object.class.base_class.to_s, thing_id: @object.id)
  64. end
  65. end
  66. end