mirror of
https://github.com/codeninjasllc/discourse.git
synced 2025-02-25 07:54:11 -05:00
Adds more helpers for plugin authors
`add_class_method` can be used to add a class method that only executes when the plugin is enabled. `add_model_callback` can be used to attach a callback to an ActiveRecord model such as `before_save` that will only execute when the plugin is enabled.
This commit is contained in:
parent
07d6bb8d31
commit
37f2d8c73c
1 changed files with 30 additions and 0 deletions
|
@ -35,6 +35,7 @@ class Plugin::Instance
|
||||||
def initialize(metadata=nil, path=nil)
|
def initialize(metadata=nil, path=nil)
|
||||||
@metadata = metadata
|
@metadata = metadata
|
||||||
@path = path
|
@path = path
|
||||||
|
@idx = 0
|
||||||
end
|
end
|
||||||
|
|
||||||
def add_admin_route(label, location)
|
def add_admin_route(label, location)
|
||||||
|
@ -62,6 +63,7 @@ class Plugin::Instance
|
||||||
end
|
end
|
||||||
|
|
||||||
# Extend a class but check that the plugin is enabled
|
# Extend a class but check that the plugin is enabled
|
||||||
|
# for class methods use `add_class_method`
|
||||||
def add_to_class(klass, attr, &block)
|
def add_to_class(klass, attr, &block)
|
||||||
klass = klass.to_s.classify.constantize
|
klass = klass.to_s.classify.constantize
|
||||||
|
|
||||||
|
@ -74,6 +76,34 @@ class Plugin::Instance
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
# Adds a class method to a class, respecting if plugin is enabled
|
||||||
|
def add_class_method(klass, attr, &block)
|
||||||
|
klass = klass.to_s.classify.constantize
|
||||||
|
|
||||||
|
hidden_method_name = :"#{attr}_without_enable_check"
|
||||||
|
klass.send(:define_singleton_method, hidden_method_name, &block)
|
||||||
|
|
||||||
|
plugin = self
|
||||||
|
klass.send(:define_singleton_method, attr) do |*args|
|
||||||
|
send(hidden_method_name, *args) if plugin.enabled?
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def add_model_callback(klass, callback, &block)
|
||||||
|
klass = klass.to_s.classify.constantize
|
||||||
|
plugin = self
|
||||||
|
|
||||||
|
# generate a unique method name
|
||||||
|
method_name = "#{plugin.name}_#{klass.name}_#{callback}#{@idx}".underscore
|
||||||
|
hidden_method_name = :"#{method_name}_without_enable_check"
|
||||||
|
klass.send(:define_method, hidden_method_name, &block)
|
||||||
|
|
||||||
|
klass.send(callback) do |*args|
|
||||||
|
send(hidden_method_name, *args) if plugin.enabled?
|
||||||
|
end
|
||||||
|
|
||||||
|
end
|
||||||
|
|
||||||
# Add validation method but check that the plugin is enabled
|
# Add validation method but check that the plugin is enabled
|
||||||
def validate(klass, name, &block)
|
def validate(klass, name, &block)
|
||||||
klass = klass.to_s.classify.constantize
|
klass = klass.to_s.classify.constantize
|
||||||
|
|
Loading…
Reference in a new issue