views:

67

answers:

3

What is the "Rails-way" or the "Ruby-way" of doing the following:

In my controller, I'm creating and instance of an Options class. It will be initialized with information in the params hash if the params hash exists. Otherwise, it will check the sessions hash for the information. Finally, it will initialize with defaults if neither params nor session has the data it needs. Here is how I'm doing it now (it works fine, but it seems a little ugly):

if params[:cust_options]
  @options = CustomOptions.new( params[:cust_options] )
else
  if session[:cust_options
    @options = CustomOptions.new( session[:cust_options] )
  else
    @options = CustomOptions.new
  end
end

session[:cust_options] = @options.to_hash

Like I said, everything is working fine, I'm just looking for a more idiomatically Ruby way of writing this block of code.


Update

This is what my code looks like now (thanks henning-koch and jdeseno):

@options = CustomOptions.new( params[:cust_options] || session[:cust_options] || {} )

If I leave the final condition (|| {}) off that line of code, what happens in my initialize method when neither params[:cust_options] nor session[:cust_options] are defined, or both are nil?

My initialize definition looks like this:

def initialize( options = {} )
  # stuff happens ...
end
+5  A: 

A shorter way to write this would be

@options = CustomOptions.new(params[:cust_options] || session[:cust_options])

Good luck.

henning-koch
If my initialize() method declaration looks like this: `def initialize( options = {} )`What happens when neither params[:cust_options] nor session[:cust_options] is defined (or is nil)?
irkenInvader
Then the value of that expression will be nil, meaning the default value will not take. You can add another "|| {}" to the expression so it will default to an empty hash.
henning-koch
+1  A: 

You can use the 'or' operator to default:

@options = CustomOptions.new( session[:cust_options] || params[:cust_options] || {} )
jdeseno
This is exactly what I was looking for.
irkenInvader
+1  A: 

You can try to put these codes in the controller that you have. Doing this will make the session key available for all the actions in the controller. It is also guaranteed that before any of the controller's action is called, the session value has been set.

# Place this under the controller class definition
before_filter :set_session_value

private

def set_session_value
  session[:cust_options] = find_cust_options_value
end

def find_cust_options_value
  return CustomOptions.new(params[:cust_options])  if params[:cust_options]
  return CustomOptions.new(session[:cust_options]) if session[:cust_options]
  return CustomOptions.new
end
SamChandra