我应该在创建对象的循环中引用实例还是 class 方法?

Should I refer to an instance or a class method in a loop that creates objects?

我正在努力将 .csv 文件导入 Rails 应用程序上的 Ruby。导入器将从文件的每一行创建一个新的数据库记录。

class Invoice < ApplicationRecord

  def self.import(file)
    output_log = []
    CSV.foreach(file.path) do |row|
      output_log << some_method_name(row)
    end
    return output_log
  end

end

我希望数据验证、记录创建和错误报告的所有复杂性都隐藏在另一种方法中,而不是弄乱我的 import 方法。我以 some_method_name 为例。我到底应该叫什么?

我想到了两种可能性。一个实例方法:

output_log << Invoice.new.populate_from_row(row)

或者,一个class方法:

output_log << Invoice.create_from_row(row)

(return 一个记录成功或失败的字符串。)

两者都可以,但哪个更有意义?是否有一些设计原则或模式应该告诉我如何选择?

我建议您在 import 方法中使用最合适的方法名称,并将所有逻辑封装在私有方法(或服务对象)中。在我的应用程序中,我通常会执行以下操作:

class Invoice < ApplicationRecord

  def self.import(file)
    output_log = []
    CSV.foreach(file.path) do |row|
      output_log << create_invoice_from_csv_row(row)
    end
    return output_log
  end

  private

  def create_invoice_from_csv_row(row)
    Invoice.find_or_create_by(
      order_number: row["Order Number"],
      customer_name: row["Customer Name"],
      # ...
    )
    return ""
  rescue => e
    return e.message
  end
end