ruby - How i can dry this code rather than put many conditions -
i'm using ror , in controller function recived params , base of operations of these params need perform action according condition. see these 18 conditions.
how can dry code.
if params[:topic] == "topic (title)" , params[:sort] == "date (asc)" # custom code elsif params[:topic] == "topic (title)" , params[:sort] == "date (desc)" # custom code elsif params[:topic] == "topic (title)" , params[:sort] == "topic (asc)" # custom code elsif params[:topic] == "topic (title)" , params[:sort] == "topic (desc)" # custom code elsif params[:topic] == "topic (title)" , params[:sort] == "author (asc)" # custom code elsif params[:topic] == "topic (title)" , params[:sort] == "author (desc)" # custom code elsif params[:topic] == "post (body)" , params[:sort] == "date (asc)" # custom code elsif params[:topic] == "post (body)" , params[:sort] == "date (desc)" # custom code elsif params[:topic] == "post (body)" , params[:sort] == "topic (asc)" # custom code elsif params[:topic] == "post (body)" , params[:sort] == "topic (desc)" # custom code elsif params[:topic] == "post (body)" , params[:sort] == "author (asc)" # custom code elsif params[:topic] == "post (body)" , params[:sort] == "author (desc)" # custom code elsif params[:topic] == "author" , params[:sort] == "date (asc)" # custom code elsif params[:topic] == "author" , params[:sort] == "date (desc)" # custom code elsif params[:topic] == "author" , params[:sort] == "topic (asc)" # custom code elsif params[:topic] == "author" , params[:sort] == "topic (desc)" # custom code elsif params[:topic] == "author" , params[:sort] == "author (asc)" # custom code elsif params[:topic] == "author" , params[:sort] == "author (desc)" # custom code end
many many thanks
if code legitimately different, consider case statement:
case [params[:topic], params[:sort]] when ["topic (title)", "date (asc)"] # custom code when ["topic (title)", "date (desc)"] # custom code when ["topic (title)", "topic (asc)"] # custom code when ["topic (title)", "topic (desc)"] # custom code when ["topic (title)", "author (asc)"] # custom code when ["topic (title)", "author (desc)"] # custom code when ["post (body)", "date (asc)"] # custom code when ["post (body)", "date (desc)"] # custom code when ["post (body)", "topic (asc)"] # custom code when ["post (body)", "topic (desc)"] # custom code when ["post (body)", "author (asc)"] # custom code when ["post (body)", "author (desc)"] # custom code when ["author", "date (asc)"] # custom code when ["author", "date (desc)"] # custom code when ["author", "topic (asc)"] # custom code when ["author", "topic (desc)"] # custom code when ["author", "author (asc)"] # custom code when ["author", "author (desc)"] # custom code end
if there repetition in code, or wind using case statement in multiple locations, there improve ways this.
ruby
No comments:
Post a Comment