开发者

Where to put custom classes in a Rails app so they are globally available?

I have a custom class located in lib and I want to create one instance of开发者_如何学编程 it that I can call anywhere in my Rails app--from controllers to rake tasks.

I can seem to do this with simple variables in an initializers file like this:

@foo = "bar"

and I can see @foo anywhere. How do I create an instance of my class so I can call it and its methods from anywhere?


In the lib directory: lib/some_thing.rb

Also see the comments in config/application.rb :

...
# Custom directories with classes and modules you want to be autoloadable. 
...


It sounds to me that you're trying to create a singleton instance of your class in lib.

Have a look at Ruby's singleton module in the ruby standard library http://www.ruby-doc.org/stdlib/libdoc/singleton/rdoc/index.html

Then you can just always access it by

SomeClass.instance

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜