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