首页 > 解决方案 > 从控制器中提取方法的位置(控制器行太多)

问题描述

在我的 Document 控制器的 create 方法中,我有一个检查参数的 if 语句,并根据每个条件创建某种类型的文档。但是,我的行太多,所以我想在其他地方提取所有这些方法并在控制器中调用它们。在阅读和环顾四周后,我仍然不确定移动这些的最佳位置。在 Rails 中处理这个问题的最佳方法是什么?

我已经修剪并简化/重命名了代码,以便更容易阅读并专注于整体想法

应用程序/控制器/documents_controller.rb

class DocumentsController < ApplicationController
  #index, show, update here

  def create
    location = Location.find(params[:id] 

    if params[:report].present?
      create_report(location)

    elsif params[:faq].present?
      create_faq(location)

    elsif params[:story].present?
      create_story(location)

    elsif params[:guide].present?
      create_guide
    end

    # a few other lines here
  end

  private
  # some methods here unrelated to creating document subtypes, but the ones below creating subtypes of documents are the ones i need to extract out 

  def create_report(location)
    @document =
      Event::CreateReport.call(
        # what we pass here changes based on the document subtype, but i just left them all the same 
        location: location,
        created_by: user,
        date: params[:date],
        text: params[:text],
        guide_stuff: 'a few more lines to pass unique subtype stuff here'
      )

    Notification::NewDocuments.new(location, user).send!
  end

  def create_faq(location)
    @document =
      Patient::CreateFaq.call(
        location: location,
        created_by: user,
        date: params[:date],
        text: params[:text],
        faq_stuff: 'unique subtype stuff here'
      )

    Notification::NewDocuments.new(location, user).send!
  end

  def create_story(location)
    @document =
      Event::CreateStory.call(
        location: location,
        created_by: user,
        date: params[:date],
        text: params[:text],
        story_stuff: 'a few more lines to pass unique subtype stuff here'
      )

    Notification::NewDocuments.new(location, user).send!
  end

  def create_guide
    @document =
      Event::CreateGuide.call(
        location: location,
        created_by: user,
        date: params[:date],
        text: params[:text],
        guide_stuff: 'a few more lines to pass unique subtype stuff here'
      )
  end
end

标签: ruby-on-railsrubycontroller

解决方案


这是一种不适合 StackOverflow 的意见问题,因为它们是高度主观的并且可以转移。不过,我不能提出一个诚实的问题,所以在不发表意见的情况下,这里有几件事需要考虑/研究:

  1. 服务对象。一些 Rails 开发人员对它们发誓,一些人认为它们被过度使用并可能导致男性型秃顶。有关它们如何工作的概述,请参阅此概述,有关相反的观点,请参阅此博客
  2. 您可能会考虑您正在执行的某些操作是否需要在请求周期中同步,或者它们是否可能是ActiveJobs 的候选对象(本质上是一种不同的服务对象)。
  3. 许多新的 Rails 开发人员倾向于将模型视为持久模型,但拥有封装行为的非持久模型并没有什么坏处。
  4. 如果你有一大块不适合“模型”或“服务对象”的可重用功能代码,那么将其放入模块中并像函数/类方法一样调用它并没有什么坏处。

推荐阅读