logo

mastofe

My custom branche(s) on git.pleroma.social/pleroma/mastofe git clone https://hacktivis.me/git/mastofe.git

scoped_settings.rb (1697B)


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