Elegant way to structure models into subfolders without creating submodules

前端 未结 10 522
一整个雨季
一整个雨季 2020-12-04 08:24

I have numerous models in my app/models folder. I\'d like to clean this folder up a little bit. Move models that belong to each other in subfolders. The problem is that by c

相关标签:
10条回答
  • 2020-12-04 09:01

    So I used to have in Rails 2 something like this:

    config.autoload_paths += Dir["#{config.root}/app/models/**/"]
    

    And the following files:

    • app/models/user/base.rb: class User::Base
    • app/models/user/admin.rb: class User::Admin

    When I upgraded to Rails 3, I kept getting an error along these lines: Expected .../app/models/user/foo.rb to define Foo. This clearly seemed crazy since Rails 2 automatically assumed that what you put in user/foo.rb would be User::Foo not just Foo.

    So the way I ended up solving this was getting rid of model subdirectories in autoload_paths and doing something like this:

    I created app/models/user.rb with:

    module User
      autoload :User, 'user/base'
      autoload :User, 'user/admin'
    end
    
    0 讨论(0)
  • 2020-12-04 09:02

    This worked for me in Rails 5.

    Adding the following to application.rb

    config.autoload_paths += Dir[ Rails.root.join('app/models/**/') ]
    

    Beware though that you cannot have the same name on your folder as any of your models.

    0 讨论(0)
  • 2020-12-04 09:08

    Until I find a better solution I've created a init.rb in the app/models folder:

    app/models/init.rb

    %w[blog].each do |folder|
      path = [File.dirname(__FILE__), folder, "*.rb"].join('/')
      Dir[path].each {|file| require file }  
    end
    

    Servers the purpose until now.

    0 讨论(0)
  • 2020-12-04 09:10

    Here is what I used for Rails 3:

    config.autoload_paths += Dir[Rails.root.join('app', 'models', '{**}')]
    

    This configuration tells Rails to scan all the app/models subfolders recursively and load all found models. No namespacing required.

    0 讨论(0)
  • 2020-12-04 09:11

    We needed to do this, and there is a very simple way.

    move your models into the sub-folders, and then tell rails to load files from all subfolders in your environment.rb file:

    config.load_paths += Dir["#{RAILS_ROOT}/app/models/*"].find_all { |f| File.stat(f).directory? }
    

    No namespacing required, and the models can be referred to as normal in your app

    0 讨论(0)
  • 2020-12-04 09:14

    Maybe you could look upon RailsEngines. It's not exactly what you need, but could gave you some ideas.

    Other than that, if your script seems to work fine (you could also just read all the files on each subfolder on model and require them), I don't see any problem against it.

    0 讨论(0)
提交回复
热议问题