I’ve moved an application to using ActiveResource and I’m finding that I need to rethink the way I’ve taught myself to do some things, and I’m searching for the best way to go about this.
For example, I need to keep a query handy say @current_account which I’ve done as
@current_account ||= Account.where(etc etc)
in an applicationcontroller.rb for a certain scope. This isn’t all that useful with AR, because the call to the API is made each time. I’d like to minimize calls to the api (especially where I have other more expensive calls I don’t want run on every query, I want to run them once and keep them handy)
So, what is the Rails way? I have to keep a variable with an AR call to an API handy from the ApplicationController in a certain scope, across several other controllers without having to write it out each time (or call the API each time, or put it in a user accesible session because it isn’t exactly text/strings, it is objects I need to use).
I’m curious about how others do this, if I should or should not be doing this, what is the right DRY way, etc. So this is somewhat open-ended.
Any input appreciated.
It’s best to create a module for this kind of behavior:
Then, make sure that Rails loads up this file (I put mine in
./lib/custom_auth.rb), so add that to theconfig.autoload_pathsin./config/application.rb:Import the
CustomAuthmodule into yourapplication_controller.rb:Finally, Crucial: Restart your server
NOTE: You can add additional methods to the
custom_auth.rb. If you restart the server, they will be available. These methods are also available in the view, so you can callcurrent_account.nameright inside a view.