jeudi 28 décembre 2017

Trying to find all classes that include a module

Before I dive into question I m gonna try to explain the structure of my codebase.

1) There might be a class X which definition would be :

module ParentModule
   class X
   end
 end

2) Also there might be a nested class under different module :

module ParentModule
   module ChildModule
     class Y
     end
   end
 end

3) Also there might be just a module with some classes inside:

module ParentModule
   module OtherModule
     def some_awesome_method
       ..does something
     end
   end  
 end

I m trying to get a list of classes within my ParentModule that include OtherModule. Here is what I have so far, working well :

include_resources = ->(klass) {
        begin
          klass_string = klass.to_s
          klass_resource = klass_string.constantize
          klass_string if klass_resource.included_modules.include?(OtherModule)
        rescue NameError # skip all bad naming and other irrelevant constant loading mishaps
          next
        end
      }

So if I do ParentModule.constants.find_all(&include_resources) I get the list of classes that include OtherModule, great! BUT unfortunately it is not able to find a class nested under child module as shown in the #2 example. So I tried doing this :

include_resources = ->(klass) {
        begin
          klass_string = klass.to_s
          klass_resource = klass_string.constantize
          if klass_resource.class == Module
            return "ParentModule::#{klass_string}".constants.find_all do |module_klass|
              module_klass.constantize.included_modules.include?(OtherModule)
            end
          end
          klass_string if klass_resource.included_modules.include?(OtherModule)
        rescue NameError # skip all bad naming and other irrelevant constant loading mishaps
          next
        end
  } 

Unfortunately this returns the same list.

Aucun commentaire:

Enregistrer un commentaire