Skip to content

Instantly share code, notes, and snippets.

@danielpowell4
Created March 9, 2017 22:16
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 danielpowell4/29d18f43ec6fe8829dcbed01aa46ba27 to your computer and use it in GitHub Desktop.
Save danielpowell4/29d18f43ec6fe8829dcbed01aa46ba27 to your computer and use it in GitHub Desktop.
This ruby script runs a SQL query and writes it as a CSV in the tmp folder using ruby's CSV library in a Ruby on Rails app
# run from console with `rails runner /path/to/this/file.rb`
# a timestamped file is placed in a Rails' app's tmp folder
require 'csv'
def file_path(name_of_file)
Rails.root.join('tmp', "#{name_of_file}_#{sanitize_time(Time.zone.now)}.csv") # don't edit name set on line 22
end
def sanitize_time(time)
time.to_s.gsub(/\s/, '_').gsub(/[\:\-]/, '')
end
def query
"SELECT *
FROM table
WHERE thing;"
end
results = ActiveRecord::Base.connection.execute(query)
CSV.open(file_path('set_file_name_with_this_string'), 'w') do |csv|
csv << ['column headers', 'as strings', 'in an array'] # replace strings with report's headers
results.each do |result|
csv << result
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment