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?
TIA
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.