Rails presence method
<p>I use Rails’ <code>present?</code> method constantly, but recently I stumbled across the <code>presence</code> method.</p> <p>In the past, I have often found myself doing the following because params[:foo] could be nil or a blank string.</p> <div class="highlight"><pre class="highlight ruby"><code><span class="n">foo</span> <span class="o">=</span> <span class="n">params</span><span class="p">[</span><span class="ss">:foo</span><span class="p">].</span><span class="nf">present?</span> <span class="p">?</span> <span class="n">params</span><span class="p">[</span><span class="ss">:foo</span><span class="p">]</span> <span class="p">:</span> <span class="s2">"something else"</span> </code></pre></div> <p>I hate that i have to write <code>params[:foo]</code> twice. But the <code>presence</code> method is handy for this case. It returns nil if the item is nil or a blank string, but otherwise returns the value.</p> <div class="highlight"><pre class="highlight ruby"><code><span class="n">foo</span> <span class="o">=</span> <span class="n">params</span><span class="p">[</span><span class="ss">:foo</span><span class="p">].</span><span class="nf">presence</span> <span class="o">||</span> <span class="s2">"something-else"</span> </code></pre></div>