简体   繁体   English

控制器中的Rails代码块,用于重复代码

[英]Rails code block in controller for repeated code

In my Rails application I am using the odf-report gem to generate reports. 在我的Rails应用程序中,我使用odf-report gem生成报告。 However I have an if condition in my method with the same 110 lines of code in each clause with one or two changes at the end. 但是,我的方法中有一个if condition ,每个子句中有相同的110行代码,最后有一个或两个更改。 I am wondering if there is a way to define the 110 lines that are being repeated in a code block and just call that code block in my main method? 我想知道是否有办法定义在代码块中重复的110行,然后在我的main方法中调用该代码块? Below is a sample of the method: 下面是该方法的示例:

def print_enrolment_form_completed
  kid = Kid.find(params[:id])
  if kid.not_anaphylactic?
    report = ODFReport::Report.new("#{Rails.root}/app/reports/Student_Enrolment_Completed.odt") do |r|
       #same 110 lines of code 
    end
  else
    report = ODFReport::Report.new("#{Rails.root}/app/reports/Student_Enrolment_Completed_Allergy.odt") do |r|
       #same 110 lines of code 
       r.add_field(:a2, kid.fish ? "Yes" : "No" )
       r.add_field(:a3, kid.eggs ? "Yes" : "No" )
       r.add_field(:a4, kid.milk ? "Yes" : "No" )
    end
  end
end

My goal is to just yield a code block where the comment is listed above and have the 110 lines defined elsewhere in the controller. 我的目标是产生一个代码块,其中的注释在上面列出,并在控制器的其他位置定义110行。 Any ideas are appreciated! 任何想法表示赞赏!

You are doing wrong, if you have 1000s of lines on controller action. 如果您在控制器操作上有1000条线路,那您做错了。 I think you should consider delayed jobs / active jobs or sidekiq or resque 我认为您应该考虑延迟的工作/现役或sidekiq或resque

Can't you just create a method containing that 110 lines of code and use it in the if statement? 您是否只能创建一个包含110行代码的方法并在if语句中使用它?

    def method_name(z, y)
      puts z + y
    end

    x = 4

    if x > 3 
      method_name(6, 7)
    else
      method_name(1, 4)
    end

Definitely agree that that many lines of code in the controller is code smell and not just for the lack of DRYness. 可以肯定的是,控制器中的许多代码行都有代码味道,而不仅仅是缺乏DRYness。

That said, you might not be in a place where you can do the full refactoring now. 也就是说,您可能不在现在可以进行完整重构的地方。 The only difference between the two branches is the string passed to the new and three lines at the end. 两个分支之间唯一的区别是传递给新行的字符串和末尾的三行。

  report = ODFReport::Report.new(kid.not_anaphylactic? ? "#{Rails.root}/app/reports/Student_Enrolment_Completed.odt" : "#{Rails.root}/app/reports/Student_Enrolment_Completed_Allergy.odt") do |r|
   #same 110 lines of code
    If kid.not_anaphylactic?
      r.add_field(:a2, kid.fish ? "Yes" : "No" )
      r.add_field(:a3, kid.eggs ? "Yes" : "No" )
      r.add_field(:a4, kid.milk ? "Yes" : "No" )
    end
 end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM