Where to initialize variables in Rails 3
I've been discovering Ruby on Rails during the last 3 months and I'm fascinated. But several things I don't know which is the best way to do them. Now I'm stack with the initialization of some variables. All the application is running over ajax, so all the instance variables should be initialize only once.
I've tried writting a method 'initialize' in the applicationController which is run just once, but the problem is that I'm accesing the request object w开发者_高级运维hich is not initialized yet.
I've tried a before_filter in the applicationController but it is run every request I do, even if it is an ajax request.
Does anyone know how to initialize an instance variable with a value from the request object? Yes, probably a newbie question.
I'm using Ruby 1.8.7 and Rails 3. Thanks in advance
I assume, you would want to do the initialization part when you land on a page and skip it for all ajax requests from the same page.
class ApplicationController < ActionController::Base
before_filter :load_vars
protected
def load_vars
unless request.xhr? #check if ajax call
# do all your initialization here
end
end
end
If the variable you're talking about is initialized from a request parameter it must need initialized for every request. So the right place to do that should be a before filter.
I've tried a before_filter in the applicationController but it is run every request I do, even if it is an ajax request.
Note that an ajax request is a normal request seen from server side, so I don't understand your "even". If the value you're checking is coming from the request param and you need it in every controller/action you really do that initialization in the ApplicationController
otherwise you could call that filter only in some controller (or even for some action only) with this syntax
# to execute it only for some actions
before_filter :your_initialization_method, :only => [:action1, :action2]
# or to exclude some actions
before_filter :your_initialization_method, :except => [:action1, :action2]
If you need to share that method across different controllers define it in ApplicationController
and do the before_filter
call only in the appropriate controllers.
You should be able to achieve this using a before filter like so:
ApplicationController < ActionController::Base
before_filter :make_it_rain
protected
def make_it_rain
@rain = 'lots'
# You should have access to 'request' in here
# Try raise request.inspect for info
end
end
You could place the before filter in a specific controller if it only applies to one part of the application, or have it run for a particular action.
精彩评论