Created
March 9, 2017 22:16
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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