Module: CopyCsv::ClassMethods
- Defined in:
- lib/copy_csv.rb
Instance Method Summary collapse
-
#copy_csv(io, relation: all) ⇒ Object
Performs a database query to copy results as CSV to an IO object.
-
#write_to_csv(file_name, mode = "w") ⇒ Object
Opens the file provided and writes the relation to it as a CSV.
Instance Method Details
#copy_csv(io, relation: all) ⇒ Object
Performs a database query to copy results as CSV to an IO object.
CSV is created directly in PostgreSQL with less overhead then written to the provided IO object.
Example
File.open("unsubscribed_users.csv", "w") do |file|
User.where(unsubscribed: false).copy_csv(file)
end
Returns nil
19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/copy_csv.rb', line 19 def copy_csv(io, relation: all) query = <<-SQL COPY (#{ relation.to_sql }) TO STDOUT WITH DELIMITER ',' CSV HEADER ENCODING 'UTF-8' QUOTE '"' SQL raw = connection.raw_connection raw.copy_data(query) do while (row = raw.get_copy_data) io.puts(ensure_utf8(row)) end end nil end |
#write_to_csv(file_name, mode = "w") ⇒ Object
Opens the file provided and writes the relation to it as a CSV.
Example
User.where(unsubscribed: false).write_to_csv("unsubscribed_users.csv")
Returns nil
41 42 43 44 45 |
# File 'lib/copy_csv.rb', line 41 def write_to_csv(file_name, mode = "w") File.open(file_name, mode) do |file| all.copy_csv(file) end end |