Coda Chang Coda Chang - 1 year ago 65
Ruby Question

Rails automatically load lib from beginning

I create a


class AwsMail

However, when I called it on
rails console
, it threw this error.

pry(main)> AwsMail
NameError: uninitialized constant AwsMail

I need to load this file by myself, so that it can be called.

Like this.

pry(main)> load "#{Rails.root}/lib/awsmail.rb"
=> true
pry(main)> AwsMail
=> AwsMail

How do I make this file automatically being loaded?

Answer Source

If a class has a name like AwsMail then file should be aws_mail.rb.

Check the good blog post Rails autoloading — how it works, and when it doesn't

In contrast with Ruby’s autoload, which requires the location of each autoloaded constant to be specified in advance, Rails follows a simple convention that maps constant names to filenames. Nesting corresponds to directories, and constant names are underscored:

MyModule::SomeClass # => my_module/some_class.rb

Also dont forget to add a lib folder to the autoload path.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download