1
0

scoped_settings.rb 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. 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. def respond_to_missing?(*)
  24. true
  25. end
  26. def all_as_records
  27. vars = thing_scoped
  28. records = vars.index_by(&:var)
  29. Setting.default_settings.each do |key, default_value|
  30. next if records.key?(key) || default_value.is_a?(Hash)
  31. records[key] = Setting.new(var: key, value: default_value)
  32. end
  33. records
  34. end
  35. def []=(key, value)
  36. key = key.to_s
  37. record = thing_scoped.find_or_initialize_by(var: key)
  38. record.update!(value: value)
  39. Rails.cache.write(Setting.cache_key(key, @object), value)
  40. end
  41. def [](key)
  42. Rails.cache.fetch(Setting.cache_key(key, @object)) do
  43. db_val = thing_scoped.find_by(var: key.to_s)
  44. if db_val
  45. default_value = ScopedSettings.default_settings[key]
  46. return default_value.with_indifferent_access.merge!(db_val.value) if default_value.is_a?(Hash)
  47. db_val.value
  48. else
  49. ScopedSettings.default_settings[key]
  50. end
  51. end
  52. end
  53. class << self
  54. def default_settings
  55. defaulting = DEFAULTING_TO_UNSCOPED.index_with { |k| Setting[k] }
  56. Setting.default_settings.merge!(defaulting)
  57. end
  58. end
  59. protected
  60. def thing_scoped
  61. Setting.unscoped.where(thing_type: @object.class.base_class.to_s, thing_id: @object.id)
  62. end
  63. end
  64. end