【问题标题】:Should this be a lone Model, a Model and Controller, or some other Ruby class entirely?这应该是一个单独的模型、模型和控制器,还是完全是其他一些 Ruby 类?
【发布时间】:2017-12-25 20:30:22
【问题描述】:

目前在我的应用程序中QuoteRequesthas_oneQuotebelongs_toQuoteRequest。 QuoteRequest 具有完整的 MVC,即QuoteRequest#new 视图使用户能够创建对象及其数据并将其保存到数据库中的 QuoteRequest 表中。

我现在正在研究如何设计下一个阶段,应该是;

  • 创建 QuoteRequest 后,它应该启动应用程序爬取到外部站点
  • 使用 QuoteRequest 数据抓取和抓取以获取报价结果,并将该结果保存到应用程序的数据库中。
  • 然后呈现该持久报价数据的视图。

作为一个新手,我正在努力决定如何最好地设计和编写这个。我相信我了解通用的 MVC 标准,即 C 为用户提供 V,V 从用户那里捕获某些内容,然后 C 获取该内容并将其发送到 M 以将其保存到数据库中。但我不确定除了这种定义的 MVC 关系之外的其他东西如何适应 Rails 环境。

在创建 QuoteRequest 后的下一个阶段中,有一部分过程不需要视图,即一旦 QuoteRequest 数据持久保存到数据库,它需要在应用程序中启动某些内容,目前 Quote没有用 Quote 编写的功能,它消失了 抓取、抓取和保存,然后我们又需要一个视图来渲染保存的抓取。

所以我想知道这个过程的“不需要视图”阶段是否应该既不是模型也不是控制器,而是某种类型的标准 Ruby 类。例如。流程如下(请原谅奇怪的“伪代码”!):

  • 在成功时QuoteRequest.save >> OtherClass.start_crawl >> 在OtherClass.crawl_success >> 保存为Quote.create(无视图)>> Quote.show(OtherClass.crawl_sucess_result) 视图 >> 完成。

谁能帮我决定如何设计这个,我想很简单,模式。谢谢

【问题讨论】:

  • Niice ho-man & widjajayd,让我在这些有用的建议背后规划和使用代码,我很快就会接受答案,希望我能接受多个答案!因为你的两个贡献真的很感激?????????。

标签: ruby-on-rails design-patterns model-view-controller


【解决方案1】:

我正在尝试使用您的“伪代码”并将控制器和 PORO(普通的旧 Ruby 对象)结合起来,下面为您的案例提供一些提示

class QuoteRequestsController < ApplicationController

  def new
    @quote_request = QuoteRequest.new
  end

  def create
    @quote_request = QuoteRequest.new(quote_request_params)
    if @quote_request.save
      flash[:success] = "QuoteRequest successful save"
      # contact other class
      @crawling_service = MyModuleService::Other.new(@quote_request) 
      @crawling_service.start_crawl
      if @crawling_service.crawl_result # if success
        # create your quote
        @quote = @quote_request.create_quote(arg1, arg2, etc)
        @quote.save
        # after save redirect_to quote show
        redirect_to quote_path(@quote)
      end
    else
      flash[:error] = @barang.errors.full_messages[0]
    end
  end
end

在 Rails 中创建 PORO 作为服务

创建 app/services 文件夹,然后你可以创建一个文件 在这个文件夹中,例如 my_module_service.rb

module MyModuleService
  attr_reader :crawl_result
  class Other
    def initialize(quote_request)
      @quote_request = quote_request
    end

    def start_crawl
      # your start crawl process
      if success
        crawl_result = true 
        # this for send message back whether success or not the crawling
      else
        crawl_result = false
      end


    end
  end
end

【讨论】:

    【解决方案2】:

    在我看来,我觉得抓取应该是一项后台任务,因此它不会占用进程。

    • 在 QuoteRequest 模型中添加 after_save(或者您也可以在控制器中调用它)
    • 也许创建一个空的Quote 对象
    • 使用后台任务库,例如 resquesidekiq
    • 编写一个 worker (activejob) 来执行爬取并使用结果更新上面的 Quote 对象。)
    • 报价的视图应该显示它在它还没有被抓取的时候正在处理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-02
      • 2021-02-27
      • 2022-09-28
      • 2010-09-09
      • 2011-08-20
      • 2011-08-29
      • 1970-01-01
      相关资源
      最近更新 更多