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:
Robin Ward 2015-08-21 11:28:17 -04:00
parent 07d6bb8d31
commit 37f2d8c73c
1 changed files with 30 additions and 0 deletions

View File

@ -35,6 +35,7 @@ class Plugin::Instance
def initialize(metadata=nil, path=nil)
@metadata = metadata
@path = path
@idx = 0
end
def add_admin_route(label, location)
@ -62,6 +63,7 @@ class Plugin::Instance
end
# Extend a class but check that the plugin is enabled
# for class methods use `add_class_method`
def add_to_class(klass, attr, &block)
klass = klass.to_s.classify.constantize
@ -74,6 +76,34 @@ class Plugin::Instance
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
def validate(klass, name, &block)
klass = klass.to_s.classify.constantize