Skip to content

Instantly share code, notes, and snippets.

@eoinkelly
Created August 20, 2021 02:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eoinkelly/8fb59047d6b9193f09bf34714822f2e5 to your computer and use it in GitHub Desktop.
Save eoinkelly/8fb59047d6b9193f09bf34714822f2e5 to your computer and use it in GitHub Desktop.
class ThingyExporter
SQL_QUERY_PATH = Rails.root.join("app/services/thingy_exporter/query.sql")
SQL_QUERY = File.read(SQL_QUERY_PATH)
HEADERS = %w[
thingy_id
tag_id
thingy_filename
survey_question_token
tag_name
tag_number
quote
start_char
end_char
tagger
tagtime
].freeze
def initialize(thingy)
@thingy = thingy
@name = thingy.name.parameterize
end
def export
log "Start DB query"
pg_conn = ActiveRecord::Base.connection.raw_connection # :: PG::Connection
pg_result = pg_conn.exec_params(SQL_QUERY, [@thingy.id]) # :: PG::Result
log "Start generating CSV"
csv_data = CSV.generate(encoding: "UTF-8", headers: HEADERS, write_headers: true, force_quotes: true) do |csv|
pg_result.each do |result_hash|
csv << result_hash
end
end
log "Finished generating CSV"
csv_data
ensure
# Clear the memory associated with the PG::Result
log "Cleaning up PG::Result memory"
pg_result.clear if pg_result
end
def log(msg)
Rails.logger.info("ThingyExporter: #{msg}")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment