Hello, I want to have an instance of a Ruby class I wrote initialized as a single instance on app startup, and have that instance accessible from my controllers. I assume this is simple, but have not been able to figure this out. Where do I initialize the class? And how can I access it from my controllers? I assume it is something like (env.rb...... '''''' $myclassinstance = MyClass.new '''''' and then (foobar-controller.rb........ '''''' def foo @myvars = $myclassinstance.mymethod( params[:somevar] ) end '''''' Thanks for reading, M --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---
M P wrote:> I want to have an instance of a Ruby class I wrote initialized as a > single instance on app startup, and have that instance accessible from > my controllers. I assume this is simple, but have not been able to > figure this out. > : > $myclassinstance = MyClass.newGlobal variables are not generally good practice. What you are describing here is a singleton pattern. This is normally implemented as a class method and class variable: class MyClass def self.the_single_instance @@the_single_instance ||= self.new end end Then use: MyClass.the_single_instance The instance will be created on the fly if it doesn''t exist and you will always get the same object each time. Note that this instance (and even any global variable you set) will be local to the thread so each mongrel instance (or whatever you use) will have it''s own copy so any data related to the object that needs to be visible to all threads should be held elsewhere (eg in the database, memcached, etc). -- Posted via http://www.ruby-forum.com/. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---