mardi 21 août 2018

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

I am working on importing a .csv file into a Ruby on Rails app. The importer will create a new database record from each row of the file.

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

I want all the complexity of data validation, record creation, and error reporting to be tucked away in another method, rather than cluttering up my import method. I'm calling some_method_name as an example. What should I really be calling?

Two possibilities occur to me. An instance method:

output_log << Invoice.new.populate_from_row(row)

Or, a class method:

output_log << Invoice.create_from_row(row)

(Either would return a string that logs success or failure.)

Both will work, but which makes more sense? Is there some design principle or pattern that should inform me about how to choose?

Aucun commentaire:

Enregistrer un commentaire