Accessing models from the lib directory in a Rails 3 project

I have a file in the lib directory that uses some constants defined in the model, for example:

class User < ActiveRecord::Base
   MAX_EMAIL_ADDRESS_LENGTH = 255
end

and then I have in lib / foo.rb

module Foo
  LONG_EMAIL_ADDRESS = "foo@bar.com".rjust(User::MAX_EMAIL_ADDRESS_LENGTH, "a")
end

Cannot find class User. How to load user before this file in lib?

I download this file having this in my .rb application:

config.autoload_paths += %W(#{config.root}/lib)
+5
source share
5 answers

The solution was that my file in / lib really needed a rake file, and it seems that the rake files are loaded before the entire auto-loading system is configured by Rails, so it cannot find the model. After removing the request from the .rake file, it all started.

+2
source

, , , , .

"Foo" , my/lib. -, , :

# in my rake file
task :foo_task do
  require /some_path/lib/bar.rb
end

# in /lib/bar.rb
puts "Foo = #{Foo.count} "

# => uninitialized constant Foo

, lib . :

task :foo_task => [:environment] do

, , Foo:

# => Foo = 6
+2

YourApplicationNameHere::Application.autoload_paths - []. ( ) glob app/models.

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

, , . , Rails, , User lib/.

Edit

.

uninitialized constant Foo::User

, Ruby/Rails User Foo. User ::, .

module Foo
  LONG_EMAIL_ADDRESS = "foo@bar.com".rjust(::User::MAX_EMAIL_ADDRESS_LENGTH, "a")
end
+1

:

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

,

module Foo
  ...
end

lib/foo.rb

.

include d.

class Comment < ActiveRecord::Base
  include Foo
  ...
end

foo.rb lib (, , ), Rails foo.rb:

require_relative "../config/environment.rb"
+1

It looks like your class user was not created, which seems unusual if you don't have "user.rb" anywhere other than "models". It often happens that classes are not loaded into development unless they are specifically located in this directory, but one of them that I use is this line, which you can only place inside your code, which you expect to call before. .

Rails.application.eager_load! if Rails.env == "development"

The conditional part is probably not needed, but I include it only to make sure that its effect occurs only during the development process.

0
source

All Articles