ruby-on-rails - 从控制器中提取方法的位置(控制器行太多)
问题描述
在我的 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
解决方案
这是一种不适合 StackOverflow 的意见问题,因为它们是高度主观的并且可以转移。不过,我不能提出一个诚实的问题,所以在不发表意见的情况下,这里有几件事需要考虑/研究:
- 服务对象。一些 Rails 开发人员对它们发誓,一些人认为它们被过度使用并可能导致男性型秃顶。有关它们如何工作的概述,请参阅此概述,有关相反的观点,请参阅此博客。
- 您可能会考虑您正在执行的某些操作是否需要在请求周期中同步,或者它们是否可能是
ActiveJob
s 的候选对象(本质上是一种不同的服务对象)。 - 许多新的 Rails 开发人员倾向于将模型视为持久模型,但拥有封装行为的非持久模型并没有什么坏处。
- 如果你有一大块不适合“模型”或“服务对象”的可重用功能代码,那么将其放入模块中并像函数/类方法一样调用它并没有什么坏处。
推荐阅读
- java - 如何配置到私有 Maven 存储库的 dbeaver 代理连接
- mysql - 如何使用 boto3 和 AWS-aurora 使用 AWS rds-data 对我的 mysql 查询进行分页?
- roblox - 如果您有 1 级或更高级别的钥匙卡,门会打开
- python - ubuntu 16.04 中 CvBridge 和 ArUco opencv 模块与 ROS 动力学相结合的问题
- cadence-workflow - 维护 Cadence 工作流程信号的顺序
- reactjs - 如何从 Laravel 在 React 中获取 json 响应?
- java - 空请求正文的 Spring bean 验证
- java - 如何解决 Java 中的 NoSuchElementException?
- node.js - 在 mongodb 中有没有办法让 insertOne 无法创建重复的索引文档而不会引发错误?
- flutter - 因为 fstore 依赖连接性 >=0.4.6+1 这需要 Flutter SDK 版本 >=1.10.0 <2.0.0