views:

141

answers:

2

If we have a before filter that's called initialize to initialize common variables, then those variables must be made into instance variables? Are there alternative ways of doing it?

Update: The situation is to validate some URL params, and set them. This used to be in one action, so everything can be done using local variables. But now, 3 actions essentially take the same params, so the code is moved to a private method validate_params, and called by using before_filter, but those local variables seem to have to be made into instance variables.

Can they be not made into instance variables? Are there frameworks / gems for validating URL params since the built-in validations are for Models.

A: 

Are there alternative ways of doing it?

Doing what, exactly? If you want a variable to be available to methods in the controller, then an instance variable would typically be appropriate. If you want to have a variable (or more likely a constant) available to all controllers, or to models and views, there are other techniques to accomplish that. We'll need more detail about the specific requirements to figure that out.

zetetic
A: 

If you want variables initialized whenever you get a new instance of an object, you can override the initialize method instead of using a callback:

class Special < ActiveRecord::Base
  attr_accessor :sauce

  def initialize(*args)
    @sauce ||= 'tomato'
    super(*args)
  end
end

Just don't forget to call super since ActiveRecords do a bunch of other stuff on initialization.

Andrew Vit