From 37f2d8c73cf9b8e09f94f750284e4c293d867581 Mon Sep 17 00:00:00 2001 From: Robin Ward Date: Fri, 21 Aug 2015 11:28:17 -0400 Subject: [PATCH] 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. --- lib/plugin/instance.rb | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/lib/plugin/instance.rb b/lib/plugin/instance.rb index caa406ec243..3c2f35cd98a 100644 --- a/lib/plugin/instance.rb +++ b/lib/plugin/instance.rb @@ -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