Ruby on rails Rails 3-重构ruby条件
我想知道在ruby中是否有更简单的方法来实现这两个条件:Ruby on rails Rails 3-重构ruby条件,ruby-on-rails,ruby,ruby-on-rails-3,refactoring,Ruby On Rails,Ruby,Ruby On Rails 3,Refactoring,我想知道在ruby中是否有更简单的方法来实现这两个条件: if params[:action] == 'index' || params[:action] == 'show' 及 提前感谢第一个可以像这样折射: if ['index', 'show'].include? params[:action] 或 对于第一个,您可以执行以下操作: if %w(index show).include?(params[:action]) 第二条应该重新分解为两行:条件检查中的赋值是一种代码气味;没有理
if params[:action] == 'index' || params[:action] == 'show'
及
提前感谢第一个可以像这样折射:
if ['index', 'show'].include? params[:action]
或
对于第一个,您可以执行以下操作:
if %w(index show).include?(params[:action])
第二条应该重新分解为两行:条件检查中的赋值是一种代码气味;没有理由这么做
如果您使用的是Rails/ActiveSupport,您可以利用Object\try
comment = session[:my_params].try(:include?, :comment)
if comment
# ... comment is in scope
end
否则,你会得到一些稍微笨重的东西:
comment = session[:my_params].include?(:comment) rescue nil
if comment
# etc
1:
2:
第二种情况下的code>和.nil?
是冗余的
但是,真的,您不应该尝试使所有内容尽可能简短,首先要关心的是您的代码对其他人的清晰程度。第二个条件应该如下所示:
if ( comment = (session[:my_params] && session[:my_params].include?(:comment) )
甚至
comment = session[:my_params] && session[:my_params].include?(:comment)
if comment
这应该比使用数组和include?
更快:
case params[:action]; when 'index', 'show'
...
end
第二条:
if comment = (session.fetch(:my_params, {}).include?(:comment))
如果session[:my_参数]为nil怎么办?这就是问题所在,但这是拯救nil的一个好方法吗?正如你所建议的那样:if(comment=(session[:my_参数].include?(:comment)rescue nil好的,Vlad。我已经修改了我的答案。条件检查中的分配操作是一种代码气味。没有理由这么做。Rescue nil是最常用的反模式之一“没有理由这么做”?这是一个非常有力的声明,我肯定不会乐意这样说,即使我不打算建议whileline=get
是一个使用它的好地方。
if ( comment = (session[:my_params] && session[:my_params].include?(:comment) )
comment = session[:my_params] && session[:my_params].include?(:comment)
if comment
case params[:action]; when 'index', 'show'
...
end
if comment = (session.fetch(:my_params, {}).include?(:comment))