在我的Document控制器的创建方法中,我有一个if语句,它检查参数,并根据每个条件创建特定类型的文档。然而,我有太多的行,所以我想在其他地方提取所有这些方法,并在控制器中调用它们。经过阅读和环顾四周,我仍然不确定移动这些东西的最佳位置。在Rails中处理这个问题的最佳方法是什么?
我对代码进行了删减和简化/重命名,使其更易于阅读,并专注于的整体想法
app/controllers/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
(本质上是不同类型的服务对象(的候选者 - 许多新的Rails开发人员倾向于将模型视为持久性的,但拥有封装行为的非持久性模型并没有坏处
- 如果你有一大块可重复使用的函数代码不适合"模型"或"服务对象",那么将其放入模块并像函数/类方法一样调用它也没有什么害处