Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails控制器重构_Ruby On Rails_Refactoring - Fatal编程技术网

Ruby on rails Rails控制器重构

Ruby on rails Rails控制器重构,ruby-on-rails,refactoring,Ruby On Rails,Refactoring,我有类似于following的代码 ... @c = M.find(params[:id]).c.find(params[:c_id]) if @c.s.count > 0 @s = @c.s.sort_by{|e| e[:order]}.first unless @s.p.nil? @img = @s.p.image_file.remote_url else @s.p = P.new @img = request.protocol + request.

我有类似于following的代码

...
@c = M.find(params[:id]).c.find(params[:c_id])
if @c.s.count > 0
  @s = @c.s.sort_by{|e| e[:order]}.first
  unless @s.p.nil?
    @img = @s.p.image_file.remote_url
  else
    @s.p = P.new
    @img = request.protocol + request.host_with_port + "/none.png"  
  end
  unless @s.a.nil?
    @voice = @s.a.audio_file.remote_url
  else
    @s.a = A.new
  end
else
 ...  
end
@c_v_url = ""
unless @c_v_url.nil?
  @c_v_url = @c.v_o.a_file.remote_url
else
  @c.v_o = A.new
end  
@c_m_url = ""
unless @c_m_url.nil?
  @c_m_url = @c.b_m.a_file.remote_url
else
  @c.b_m = A.new
end
...

现在,所有的实例变量都将在视图中使用,我想重新考虑代码,使控制器变瘦。进行重新分解的最佳方法是什么?将此代码移到模型中是否明智?

我看不出此代码的真正用途,但它看起来像是显示图像、文件和音频链接的视图逻辑

我将为每个视图创建一个视图帮助器方法,例如:

 def s_image_url(s)
   unless s.p.nil?
     s.p.image_file.remote_url
   else
     request.protocol + request.host_with_port + "/none.png"  
   end
 end

有关

的更多信息,我将使用Presenter模式,这里有一些资源可供解释(还有很多):


  • 简短的故事:您将检索模型的所有逻辑都放在presenter中。演示者易于测试和扩展。在控制器中,操作将只有一行代码来实例化演示者。

    这部分解决了我的问题,但如果必须,我将这个完整的if/else逻辑移动到哪里。