Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 - Refactor ruby conditions

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

like image 978
invaino Avatar asked Dec 08 '25 23:12

invaino


2 Answers

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
like image 152
dnch Avatar answered Dec 11 '25 12:12

dnch


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 
like image 24
Vlad Khomich Avatar answered Dec 11 '25 12:12

Vlad Khomich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!