How to make my Rails variable accessible to the entire app?
I'am using the Gmail Gem. I dont want to run Gmail.connect every time I will request data from gmail. I want to store the connection into a variable so I could access it anywhere into the application.
First attempt, I stored it into a global variable @gmail_session but I can't access the variable after when I tried to get it using a remote call.
Second attempt, I saved the connection in to a session variable session[:gmail]. I thought it would be the solution but I got this error me开发者_运维百科ssage: no marshal_dump is defined for class Thread
Please help me store my Gmail Connection :)
Thanks!
Rails newb here, so there might be a better way out there, but here's my 20 on this..
Use the application_controller to create a method that loads the @gmail_session object there itself, that way its an instance var and available to all controllers/views.
For e.g.
def get_using_remote_call
@gmail_session = //do some stuff
end
Then you can go ahead and add an after_filter in the application_controller that calls the function every time any of the controllers load, since after their first load in production they are cached, this should not pose a problem until your app gets 10000s visits a day...
Another way of doing the same thing would be to include a module in the config/libs and add the directory to autoload in your config/application.rb like this
config.autoload_paths += %W(#{config.root}/lib)
This would auto load the module/class/whatever and then you can simply call the function get_using_remote_call
and treat it as an object and chain it, or your could
@gmail_session = get_using_remote_call
OR simply use this in the after_filter/before_filter of your controller :)
Hope this helps!
精彩评论