Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I assign a value from params, or session, whichever exists?
    primarykey
    data
    text
    <p>What is the "Rails-way" or the "Ruby-way" of doing the following:</p> <p>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):</p> <pre><code>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 </code></pre> <p>Like I said, everything is working fine, I'm just looking for a more idiomatically Ruby way of writing this block of code.</p> <hr> <h2>Update</h2> <p>This is what my code looks like now (thanks <a href="https://stackoverflow.com/users/340168/henning-koch">henning-koch</a> and <a href="https://stackoverflow.com/users/324312/jdeseno">jdeseno</a>):</p> <pre><code>@options = CustomOptions.new( params[:cust_options] || session[:cust_options] || {} ) </code></pre> <p>If I leave the final condition (<code>|| {}</code>) off that line of code, what happens in my <code>initialize</code> method when neither params[:cust_options] nor session[:cust_options] are defined, or both are <code>nil</code>?</p> <p>My <code>initialize</code> definition looks like this:</p> <pre><code>def initialize( options = {} ) # stuff happens ... end </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload