DEV: Improve add_to_serializer include_* options (#21073)

- Move the old '`define_include_method`' arg to a `respect_plugin_enabled` kwarg
- Introduce an `include_condition` kwarg which can be passed a lambda with inclusion logic. Lambda will be run via `instance_exec` in the context of the serializer instance

This is backwards compatible - old-style invocations will trigger a deprecation message

Update chat and poll plugins to new pattern
This commit is contained in:
David Taylor
2023-04-24 06:47:28 +01:00
committed by GitHub
parent f7bc30a37d
commit 4895e76ef7
4 changed files with 113 additions and 53 deletions

View File

@ -109,7 +109,27 @@ class Plugin::Instance
delegate :name, to: :metadata
def add_to_serializer(serializer, attr, define_include_method = true, &block)
def add_to_serializer(
serializer,
attr,
deprecated_respect_plugin_enabled = nil,
respect_plugin_enabled: true,
include_condition: nil,
&block
)
if !deprecated_respect_plugin_enabled.nil?
Discourse.deprecate(
"add_to_serializer's respect_plugin_enabled argument should be passed as a keyword argument",
)
respect_plugin_enabled = deprecated_respect_plugin_enabled
end
if attr.to_s.starts_with?("include_")
Discourse.deprecate(
"add_to_serializer should not be used to directly override include_*? methods. Use the include_condition keyword argument instead",
)
end
reloadable_patch do |plugin|
base =
begin
@ -123,9 +143,13 @@ class Plugin::Instance
unless attr.to_s.start_with?("include_")
klass.attributes(attr)
if define_include_method
if respect_plugin_enabled || include_condition
# Don't include serialized methods if the plugin is disabled
klass.public_send(:define_method, "include_#{attr}?") { plugin.enabled? }
klass.public_send(:define_method, "include_#{attr}?") do
next false if respect_plugin_enabled && !plugin.enabled?
next instance_exec(&include_condition) if include_condition
true
end
end
end