【问题标题】:rails: keep it DRY, to what level? [closed]rails:保持干燥,达到什么水平? [关闭]
【发布时间】:2018-08-14 05:36:41
【问题描述】:

我们总是读到人们说用铁轨“保持干燥”。但是到什么水平呢?

例如,我们有 3 个模型 ProjectOfferRevision。这3个模型可以有多个Attachment

在“模型”方面,我们最终得到了非常直接的结果

/app/models/project.rb
/app/models/offer.rb
/app/models/revision.rb

但是对于控制器方面,我很难保持干燥。我最终得到了至少:

GET  /projects/:id/attachments    ->   Projects/Attachments#index
POST /projects/:id/attachments    ->   Projects/Attachments#create
GET  /offers/:id/attachments      ->   Offers/Attachments#index
POST /offers/:id/attachments      ->   Offers/Attachments#create
GET  /revisions/:id/attachments   ->   Revisions/Attachments#index
POST /revisions/:id/attachments   ->   Revisions/Attachments#create

所以基本上,我在这 3 个位置的代码几乎相同:

controllers/projects/attachments_controller.rb
controllers/offers/attachments_controller.rb
controllers/revisions/attachments_controller.rb

我的问题,我应该把它弄干吗?怎么弄?

【问题讨论】:

    标签: ruby-on-rails model-view-controller controller dry


    【解决方案1】:

    DRY 或“不要重复自己”是一般的经验法则。

    如果您发现代码中的某个模式在多个地方重复出现,则可能值得研究一下。

    如果可以将通用功能提取到模块中,那么您应该这样做。

    如果你认为这不值得你花时间、复杂或任何理由不去做,那​​完全没问题。

    KISS(保持简单和愚蠢)> DRY

    确保您的代码易于遵循、重构并在之后干燥。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 2011-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多