2

I'm interested in how Rails automatically loads the modules in app/helpers into models.

To wit: when app/helpers/widget_helper.rb exists and contains WidgetHelper that module is automatically loaded into the Widget model.

I have need of a directory in app that contains arbitrary code for inclusion into models, and would like to avoid having to include every individual module. I thought mocking this functionality would be useful.

JohnMetta
  • 18,782
  • 5
  • 31
  • 57

1 Answers1

0

Still not sure how Helpers are loaded, but I spent some time figuring out a good way to do this given the rails config.after_initialize call.

Given that you want to have an app/goods directory with ModelGoods named modules that are auto-loaded. Add the following code to application.rb:

config.after_initialize do
  Dir["#{Rails.root}/app/goods/*_goods.rb"].each do |file|
    name = File.basename(file, ".rb").humanize.titleize.gsub(" ","")
    name.gsub("Goods","").constantize.send :include, "Goods::#{name}".constantize
  end
end

This will parse all files in the app/goods subdirectory and include the module for any model named that is included in that directory.

Obviously, you can replace "Goods" with whatever you want, but this represents a decent way to compartmentalize code without having to manually include every module you create.

JohnMetta
  • 18,782
  • 5
  • 31
  • 57