Skip to content

Instantly share code, notes, and snippets.

@michaelminter
Created April 29, 2019 17:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaelminter/c4ece37ccc750e12093275948f1b19e0 to your computer and use it in GitHub Desktop.
Save michaelminter/c4ece37ccc750e12093275948f1b19e0 to your computer and use it in GitHub Desktop.
Upload CSV stream from Rails to S3
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