Gabriel Mazetto
Gabriel Mazetto

Reputation: 1130

Ruby on Rails: Autoloading models from external folder fails on Rails 3.1, 3.2

What I'm basically doing is sharing some models across multiple projects. I have a base project where all models are defined and some other projects that requires thous models, as all of them use the same data.

By that said, what I used to do is define a config.autoload_paths pointing to the other projects model folder:

config.autoload_paths += %W(#{config.root}/../base_project/app/models)

With Rails 3.0 it works perfectly fine, however with Rails 3.1, 3.2, I get uninitialized constnat to every model name, for example:

NameError (uninitialized constant ApplicationController::User):
  app/controllers/application_controller.rb:11:in `current_user'

How can I fix it without duplicating the files or symbolic linking them?

FYI, i've filled a bug here: https://github.com/rails/rails/issues/5007

Upvotes: 1

Views: 516

Answers (1)

fdsaas
fdsaas

Reputation: 714

You can try loading the models with require_dependency. Maybe as the application load you could do the following. (require_dependency is part of Rails, and different than require.)

Dir.glob(File.join(config.root, "**", "*.rb")) { |filename| require_dependency filename }

This however might not be ideal.

Another more common (and arguably better) solution would be to package your models and make them available as a gem.

# Gemfile of some project
gem 'shared_models_by_gabriel', :path => 'xxx'

Where xxx could be a path to a Github repository, a Bitbucket repository, the vendor directory, or otherwise. (Although you should be aware of Rails 4 plans for vendor.)

Upvotes: 1

Related Questions