你将如何整理这个控制器逻辑? [英] How would you tidy up this controller logic?
问题描述
如果满足某些条件,我在控制器中设置了一个逻辑来设置对象的状态:
I've got some logic in a controller that sets a status of an object if certain conditions are met:
if params[:concept][:consulted_legal] == 0 && params[:concept][:consulted_marketing] == 1
@concept.attributes = {:status => 'Awaiting Compliance Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 1
@concept.attributes = {:status => 'Awaiting Marketing Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 0
@concept.attributes = {:status => 'Awaiting Marketing & Legal Approval'}
else
@concept.attributes = {:status => 'Pending Approval'}
end
你将如何去重构这种???寻找最佳做法。
that I share between create and update actions. How would you go about refactoring this nastiness? Looking for best practices.
刚开始编程,热衷于清理我的代码。
New to programming and keen to clean up my code.
TIA。
推荐答案
我称之为超级DRY。
statuses =
[
['Awaiting Marketing & Legal Approval','Awaiting Compliance Approval'],
['Awaiting Marketing Approval','Pending Approval']
]
{:status => statuses[params[:concept][:consulted_legal].to_i][params[:concept][:consulted_marketing].to_i]}
或者,一种更传统的方法 - 冗长但可读:
Alternatively, a more conventional approach -- lengthy but readable:
status = if params[:concept][:consulted_legal] == "0"
if params[:concept][:consulted_marketing] == "1"
'Awaiting Compliance Approval'
else
'Awaiting Marketing & Legal Approval'
end
else
if params[:concept][:consulted_marketing] == "0"
'Awaiting Marketing Approval'
else
'Pending Approval'
end
end
@concept.attributes = {:status => status}
注意:看起来您的原始代码正在检查值复选框。 params
哈希中的值始终 字符串
,而不是 Fixnum
因此我的代码比较字符串。如果由于某些原因比较 Fixnum
s是您的情况需要的,只需取出数字周围的引号。
Note: It looks like your original code is checking values of check boxes. Values in the params
hash are always Strings
, not Fixnum
s so my code compares strings. If for some reason comparing Fixnum
s is what is required for your situation, just take out the quotes around the numbers.
这篇关于你将如何整理这个控制器逻辑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!