0

我有一个 ActiveRecord 模型Reservation
它已经到了班级太大并且做得太多的地步。
我想将它分成几个不同的并将它们放在Reservation模块下。

不幸的是,这会破坏应用程序。

此刻,我看到以下选项:

  • 将其命名为类似ReservationConcerns或类似的东西
  • 将功能添加到Reservation类本身,但将其物理移动到子目录(Reservation将在app/models/reservation.rbReservation::Pipeline将在app/models/reservation/pipeline.rb等)。

所以问题是如何在不破坏应用程序的情况下,将已经拥有的功能的不同关注点构建为一个单一的、庞大的类。

4

1 回答 1

0

If you want to split up a Ruby class into different components without changing its public interface, one solution is to use modules:

# app/models/reservation.rb
class Reservation < ActiveRecord::Base
  # associations, validations, etc.

  include Pipeline
end

# app/models/reservation/pipeline.rb
module Reservation::Pipeline
  def some_pipeline_method
    # ...
  end

  def other_pipeline_method
    # ...
  end
end

ActiveRecord also provides observers, which "is a great way to reduce the clutter that normally comes when the model class is burdened with functionality that doesn't pertain to the core responsibility of the class". Observers often make heavy use of the ActiveModel::Dirty methods.

These suggestions are complimentary: modules can help you group your interface into more local chunks, while observers can make backend details more self-contained. From here, it's difficult to be more specific without knowing exactly what pieces you have that you're trying to break out.

于 2012-10-17T03:02:10.997 回答