我在控制器中有一些逻辑,如果满足某些条件,则设置对象的状态:
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
我在创建和更新操作之间共享.你会如何重构这种肮脏的东西?寻找最佳实践.
编程新手并热衷于清理我的代码.
TIA.
您可以使代码减少对两种条件的依赖,并使其更加灵活.
waiting_on = [] waiting_on << 'Compliance' unless params[:concept][:consulted_marketing] waiting_on << 'Legal' unless params[:concept][:consulted_legal] status = waiting_on.empty? ? "Awaiting #{waiting_on.join(' & ')} Approval" : 'Pending Approval' @concept.attributes = {:status => status}
无过滤器的创建和更新版本:
def create set_concept_status_attribute ... end def update set_concept_status_attribute ... end private def set_concept_status_attribute waiting_on = [] waiting_on << 'Compliance' unless params[:concept][:consulted_marketing] waiting_on << 'Legal' unless params[:concept][:consulted_legal] status = waiting_on.empty? ? "Awaiting #{waiting_on.join(' & ')} Approval" : 'Pending Approval' @concept.attributes = {:status => status} end
或者使用before_filter:
before_filter :set_concept_status_attribute, :only => [:create, :update] def create ... end def update ... end
如果你可以将它移动到你的视图,它看起来更好:
module ConceptHelper def get_concept_status ... end end <%= get_concept_status %>