开发者

How do I reference a custom class in lib from one of my models?

If I create a file in lib/ called toast_mitten.rb, and in that file I have a class called ToastMitten, how do I use that class from my models?

For example, inside a method on the Comments class (one of my models), if I try to call ToastMitten.gra开发者_运维百科sp, I get an error like uninitialized constant Comment::ToastMitten.

The class I created is intended to DRY up some repeated code in both my models and a rake task.


Rails 3 doesn't autoload lib

The problem was that lib was not being autoloaded. I'm using Rails 3.0.0. Apparently, the Rails team decided to stop autoloading lib in Rails 3, as José Valim says here.

To get it to load, I added this to application.rb:

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

My colleague tells me that my other options would be:

  • Add it to config/initializers
  • Explicitly require it in the model where I want to use it


It should work like that, so if you get an error try to restart the server, or check for typos. It would be helpful if you showed the toast_mitten file

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜