Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including all modules in a directory in Ruby 1.9.2

Tags:

ruby

I've placed a set of .rb files in a directory modules/. Each of these files contains a module. I'm loading all of these files from a separate script with this:

Dir["modules/*.rb"].each {|file| load file }

But then I have to include them, one by one, listing and naming each of them explicitly:

class Foo
  include ModuleA
  include ModuleB
  # ... and so on.
end

I'm wondering if there is some non-explicit one-liner that can accomplish this, a la (pseudocode) ...

class Foo
  for each loaded file
    include the module(s) within that file
  end
  # ... other stuff.
end

I've considered actually reading the files' contents, searching for the string "module", and then extracting the module name, and somehow doing the include based on that -- but that seems ridiculous.

Is what I'm trying to do advisable and/or possible?

like image 364
GladstoneKeep Avatar asked Nov 05 '22 23:11

GladstoneKeep


1 Answers

You can manually define some variable in each of your file and then check for its value while including the file.

For example, module1.rb:

export = ["MyModule"]

module MyModule

end

And the second one, module2.rb:

export = ["AnotherModule", "ThirdModule"]

module AnotherModule

end

module ThirdModule

end

And then just include all of them in your file (just the idea, it may not work correctly):

class Foo
    Dir["modules/*.rb"].each do |file| 
        load file
        if export != nil
             export.each do { |m| include(Kernel.const_get(m))
        end 
    end
end
like image 198
Daniel O'Hara Avatar answered Nov 09 '22 11:11

Daniel O'Hara