scoped_settings.rb 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # frozen_string_literal: true
  2. module Settings
  3. class ScopedSettings
  4. DEFAULTING_TO_UNSCOPED = %w(
  5. theme
  6. ).freeze
  7. def initialize(object)
  8. @object = object
  9. end
  10. # rubocop:disable Style/MethodMissing
  11. def method_missing(method, *args)
  12. method_name = method.to_s
  13. # set a value for a variable
  14. if method_name[-1] == '='
  15. var_name = method_name.sub('=', '')
  16. value = args.first
  17. self[var_name] = value
  18. else
  19. # retrieve a value
  20. self[method_name]
  21. end
  22. end
  23. # rubocop:enable Style/MethodMissing
  24. def respond_to_missing?(*)
  25. true
  26. end
  27. def all_as_records
  28. vars = thing_scoped
  29. records = vars.each_with_object({}) { |r, h| h[r.var] = r }
  30. Setting.default_settings.each do |key, default_value|
  31. next if records.key?(key) || default_value.is_a?(Hash)
  32. records[key] = Setting.new(var: key, value: default_value)
  33. end
  34. records
  35. end
  36. def []=(key, value)
  37. key = key.to_s
  38. record = thing_scoped.find_or_initialize_by(var: key)
  39. record.update!(value: value)
  40. Rails.cache.write(Setting.cache_key(key, @object), value)
  41. 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