Calling a class method with a layered module structure in Ruby

I have some modules that will be included in my controller classes. These modules define before_filter :

 module BasicFeatures def filter_method ... end def self.included(base) base.before_filter(:filter_method) ... end end module AdvancedFeatures include BasicFeatures ... end 

And classes:

 class BasicController < ApplicationController include BasicFeatures end class AdvancedController < ApplicationController include AdvancedFeatures end 
  • When the BasicFeatures module BasicFeatures included in the AdvancedFeatures module, it does not have before_filter methods.
  • AdvancedController did not receive a call before_filter .

I need both of my controllers to get before_filter without duplicating code. I do not know if I am using the best approach, so I am open to any suggestion.

+4
source share
2 answers

This is why ActiveSupport::Concern was created.

 module BasicFeatures extend ActiveSupport::Concern included do before_filter :require_user end def this_is_an_instance_method 'foo' end module ClassMethods def this_is_a_class_method 'bar' end end end class SomeClass include BasicFeatures end SomeClass.new.this_is_an_instance_method #=> 'foo' 

You can also nest them, that is, create problems that include problems - and everything will work as expected. And here are the documents .

+5
source

You can try this. Instead of including the module in AdvancedFeatures, you can include the BasicFeatures module in the class, including AdvancedFeatures

 module BasicFeatures def filter_method #code.... end #some others basic methods... def self.included(base) base.before_filter(:filter_method) #some other class method calls end end module AdvancedFeatures def self.included klass klass.class_eval do include BasicFeatures end end #some advanced methods end 
0
source

Source: https://habr.com/ru/post/1494067/


All Articles