use*_*721 3 ruby refactoring ruby-on-rails
我尝试阅读一些有关重构的教程,但我在条件方面苦苦挣扎。我不想使用三元运算符,但也许应该将其提取为方法?还是有使用地图的聪明方法?
detail.stated = if value[:stated].blank?
nil
elsif value[:stated] == "Incomplete"
nil
elsif value[:is_ratio] == "true"
value[:stated] == "true"
else
apply_currency_increment_for_save(value[:stated])
end
Run Code Online (Sandbox Code Playgroud)
如果将此逻辑移至方法中,则可以通过使用早期return(和关键字参数)使它变得更加整洁:
def stated?(stated:, is_ratio: nil, **)
return if stated.blank? || stated == "Incomplete"
return stated == "true" if is_ratio == "true"
apply_currency_increment_for_save(stated)
end
Run Code Online (Sandbox Code Playgroud)
然后...
detail.stated = stated?(value)
Run Code Online (Sandbox Code Playgroud)