Search code examples
ruby-on-railsrubymetaprogrammingredmineredmine-plugins

Add private method to class by mixin


I want to add an after_create callback to Role model by my plugin. So I can add an after_callback :my_private_method by class_eval as usual. I can add public method by defining it in InstanceMethods in the module that mixined in Role model.

But how I can add a private method my_private_method to Role model for using in after_create callback?

I know that this can be implemented by class_eval but is there any nicer solution?


Solution

  • Oh it was really easy:

    module RolePatch
      module InstanceMethods
        private    <<<<<<<<<<<<<<<<<<<<<<<<<<<<   It works like a charm.
        def my_private_method; end
      end
    
      def self.included(receiver)
        receiver.send :include, InstanceMethods
    
        receiver.class_eval do
          after_create :my_private_method
        end
      end
    end
    
    1.9.3p392 :017 > Role.first.private_methods.grep(/my_private_method/)
     => [:my_private_method]
    

    So we can use private modifier in module InstanceMethods as usual.