inv*_*ino 3 ruby refactoring ruby-on-rails ruby-on-rails-3
我想知道是否有更简单的方法在ruby中执行这两个条件:
if params[:action] == 'index' || params[:action] == 'show'
Run Code Online (Sandbox Code Playgroud)
和
if !(comment = (session[:my_params].include?(:comment) rescue nil)).nil?
Run Code Online (Sandbox Code Playgroud)
提前致谢
对于第一个,您可以这样做:
if %w(index show).include?(params[:action])
Run Code Online (Sandbox Code Playgroud)
第二个应该真正重新分为两行:条件检查中的赋值是代码气味; 从来没有理由.
如果您正在使用Rails/ActiveSupport,则可以利用 Object#try
comment = session[:my_params].try(:include?, :comment)
if comment
# ... comment is in scope
end
Run Code Online (Sandbox Code Playgroud)
否则,你会留下一些略显笨拙的东西:
comment = session[:my_params].include?(:comment) rescue nil
if comment
# etc
Run Code Online (Sandbox Code Playgroud)