Add existing classes into a module

前端 未结 5 2102
无人及你
无人及你 2020-12-17 02:37

I have some existing ruby classes in a app/classes folder:

class A
   ...
end

class B
   ...
end

I\'d like to group those classes in a mod

5条回答
  •  一整个雨季
    2020-12-17 02:42

    If you do want to put them in a module I don't see the point of first including them in the global namespace and then aliasing them inside the module. I think what you want to do (although I doubt it is a good thing to do) is something like this:

    file classes/g1.rb

    class A1
      def self.a
        "a1"
      end
    end
    
    class B1
      def self.b
        "b1"
      end
    end
    

    file classes/g2.rb

    class A2
      def self.a
        "a2"
      end
    end
    
    class B2
      def self.b
        "b2"
      end
    end
    

    file imp.rb

    module MyModule
      ["g1.rb", "g2.rb"].each do |file|
        self.class_eval open("classes/#{file}"){ |f| f.read }
      end
    end
    
    puts defined? MyModule
    puts defined? A1
    puts defined? MyModule::A1
    
    puts MyModule::A1.a
    puts MyModule::B2.b
    

    outputs

    constant
    nil
    constant
    a1
    b2
    

    I can think of a few disadvantages of this approach (harder to debug for one thing, and probably a bit slower to load although I am only guessing).

    Why don't you just do something like this:

    Dir["classes/*.rb"].each do |file|
      contents = open(file) { |f| f.read }
      open(file, "w") do |f| 
        f.puts "module MyModule\n"
        contents.each { |line| f.write "  #{line}" }
        f.puts "\nend"
      end
    end
    

    That'll fix your classes to be in your module since in ruby you can reopen a module at any time. Then just include them like you do normally.

提交回复
热议问题