I have a file in the lib directory that uses some constants defined in a model, like:
class User < ActiveRecord::Base
MAX_EMAIL_ADDRESS_LENGTH = 255
en
By default, YourApplicationNameHere::Application.autoload_paths
is []
. I (purely for organizational reasons) add a glob for my app/models
directory too.
config.autoload_paths += Dir["#{Rails.root}/app/models/**/"]
config.autoload_paths += Dir["#{config.root}/lib"]
With this setup I'm able to do what you're asking in the Question without trouble. This should benefit you as well, telling Rails where to look if it can't find the User
model from within your lib/
module's instantiation.
Edit
Specifying the exact error message in your question would have helped too.
uninitialized constant Foo::User
means Ruby/Rails is looking for User
within the Foo
namespace. Prefix User
with ::
to force the lookup to the global namespace.
module Foo
LONG_EMAIL_ADDRESS = "foo@bar.com".rjust(::User::MAX_EMAIL_ADDRESS_LENGTH, "a")
end