任何想法我怎么能重构这段代码?
case @fruit.actable_type
when "Apple"
redirect_to apple_path(@fruit.specific, :anchor => "comment_id_#{@comment.id}")
when "Orange"
redirect_to orange_path(@fruit.specific, :anchor => "comment_id_#{@comment.id}")
when "Banana"
redirect_to banana_path(@fruit.specific, :anchor => "comment_id_#{@comment.id}")
end
主要问题是要指定我需要包含路径的锚点,我不能这样做:
redirect_to @fruit.specific, anchor: "whatever"
我尝试了很多东西,但我仍然无法重构:/
答案 0 :(得分:2)
path_method = "#{@fruit.actable_type.downcase}_path"
anchor = "comment_id_{@comment.id}"
redirect_to send(path_method, @fruit.specific, anchor: anchor)
答案 1 :(得分:2)
这样的事情对你有用:
anchor = "comment_id_#{@comment.id}"
prefix = @fruit.actable_type.downcase
redirect_to send("#{prefix}_path", @fruit.specific, anchor: anchor)