I'd like to know if there is a simpler way to do these 2 conditions in ruby :
if params[:action] == 'index' || params[:action] == 'show'
and
if !(comment = (session[:my_params].include?(:comment) rescue nil)).nil?
Thanks in advance
For the first one, you could do:
if %w(index show).include?(params[:action])
The second should really be re-factored into two lines: assignment within a condition check is a code smell; there's never a reason for it.
If you're using Rails / ActiveSupport, you can take advantage of Object#try
comment = session[:my_params].try(:include?, :comment)
if comment
# ... comment is in scope
end
Otherwise, you're left with something slightly clunkier:
comment = session[:my_params].include?(:comment) rescue nil
if comment
# etc
1:
if ['index','show'].include? params[:action]
2:
if (comment = (session[:my_params].include?(:comment) rescue nil))
! and .nil? in second condition are redundant
But, really, you should not try to make everything as short as possible, the first thing to care about is how clear your code would be for other people. The second condition should look like:
if ( comment = (session[:my_params] && session[:my_params].include?(:comment) )
or even
comment = session[:my_params] && session[:my_params].include?(:comment)
if comment
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With