闭社主体 forked from https://github.com/tootsuite/mastodon
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.

80 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/MethodMissing
  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/MethodMissing
  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. value
  43. end
  44. def [](key)
  45. Rails.cache.fetch(Setting.cache_key(key, @object)) do
  46. db_val = thing_scoped.find_by(var: key.to_s)
  47. if db_val
  48. default_value = ScopedSettings.default_settings[key]
  49. return default_value.with_indifferent_access.merge!(db_val.value) if default_value.is_a?(Hash)
  50. db_val.value
  51. else
  52. ScopedSettings.default_settings[key]
  53. end
  54. end
  55. end
  56. class << self
  57. def default_settings
  58. defaulting = DEFAULTING_TO_UNSCOPED.each_with_object({}) { |k, h| h[k] = Setting[k] }
  59. Setting.default_settings.merge!(defaulting)
  60. end
  61. end
  62. protected
  63. def thing_scoped
  64. Setting.unscoped.where(thing_type: @object.class.base_class.to_s, thing_id: @object.id)
  65. end
  66. end
  67. end