1

I have module in /lib/models/scopes.rb

module Models
    module Scopes
        extend ActiveSupport::Concern
        ...
    end
end

I'm trying to include it from model:

class User < ActiveRecord::Base
  include Models::Scopes
end

And getting error:

NameError: uninitialized constant User::Models

How to solve this trouble? Maybe it`s wrong to keep this types of files in /lib?

Environment: Rails v3.1 Ruby v1.9.3

2 Answers 2

8

Rails doesn't require files in the lib directory automatically, but you can add to the autoloaded paths in config/application.rb:

config.autoload_paths += %W(#{config.root}/lib)

Restart the server to pick up the new settings.

This will now load the file automatically when the module name is first used. In development mode, you might want to reload the module after every change in order to see the changes without restarting the server. To do that, add it as an eager load path instead:

config.eager_load_paths += %W(#{config.root}/lib)

The scope shouldn't be a problem as long as you don't have a Models class or module within User or anywhere else.

Sign up to request clarification or add additional context in comments.

Comments

2

when you define your class, you're "opening" a new scope. So when you do Models::Scopes, ruby is looking for User::Models::Scopes. You can fix this by using ::Models::Scopes, the :: telling ruby to look in the global scope.

FYI: I'm not sure about the terms I used or even if my train of thought if correct; but the solution should be good anyway. I'd think Ruby would try for ::Models::Scope after failing to find User::Models::Scope, but it doesn't.. Maybe there is a User::Models scope defined somewhere? Anyway, as you can see, I'm not yet familiar with those. You might want to dig on the subject if that interests you

2 Comments

Thank you for answer. But now, with ::Models:Scopes, Rails throw "NameError: uninitialized constant Models"
then you should refer to @SMWEB answer. I skipped the part where your is in /lib. You first code should have worked fine if your file was loaded.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.