Created
April 29, 2019 17:40
-
-
Save michaelminter/c4ece37ccc750e12093275948f1b19e0 to your computer and use it in GitHub Desktop.
Upload CSV stream from Rails to S3
This file contains hidden or 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
def query_results | |
ActiveRecord::Base.connection.execute('SELECT name FROM accounts;').to_a | |
end | |
# @params [Array<Hash>] records | |
def generate_csv(records) | |
attributes = records.first.keys | |
CSV.generate(headers: true) do |csv| | |
csv << attributes | |
records.each do |record| | |
csv << record | |
end | |
end | |
end | |
# requires aws-sdk | |
def prepare_s3 | |
Aws.config.update( | |
{ | |
region: 'us-west-2', | |
credentials: Aws::Credentials.new(ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY']), | |
} | |
) | |
end | |
def export(data, bucket_name, file_name) | |
object = Aws::S3::Resource.new.bucket(bucket_name).object(file_name) | |
object.put(body: data) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment