简体   繁体   中英

How to stay DRY with a Ruby on Rails model?

Several objects of my application need to be exported as CSV. Based on #362 Exporting CSV and Excel I added the following function to a model:

### private functions definitions
private

def self.to_csv
  CSV.generate(:col_sep => ";") do |csv| #Could accept a separator option
    csv << column_names
    all.each do |column|
      csv << column.attributes.values_at(*column_names)
    end
  end
end

How can I, at model level, reuse this function for other models ?

Thanks.

You can define a module with common methods:

module CsvHelper
  def to_csv
    CSV.generate(:col_sep => ";") do |csv| #Could accept a separator option
      csv << column_names
      all.each do |column|
        csv << column.attributes.values_at(*column_names)
      end
    end
  end
end

And now use in classes:

extend CsvHelper

PS class's methods' scope does not change with private in the scope of the class.

If you really want to have a private singleton method, you'd do the following:

class Foo
  class << self
    private

    def bar
    end
  end
end

Now bar method is private.

If this application is more than a toy project, i'd recommend using something like the comma gem https://github.com/comma-csv/comma

This will work well for exports of hundreds and should be ok for a couple thousand rows if you eager-load all associations and there isn't any dependent queries.

If you need to worry about generating files with hundreds of thousands or millions of rows, you should consider running these in a background job or, if you're using DB like postgres, taking advantage of postgres' built-in CSV generation which is very fast. There's a nice gem that makes this process pretty painless: https://github.com/diogob/postgres-copy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM