Export JSON static data to Amazon S3 and retrieve it through AJAX

In my Rails 3 application, I would like to export static JSON data to an Amazon S3 bucket, which can then be retrieved and parsed using an AJAX call from the specified application.

JSON will be created from the application database.

My design requirements will probably require something like a rake task to initiate export to S3. Each time the rake task runs, it overwrites the files. Preferably, the file name will correspond to the identification number of the record from which the JSON data is generated.

Does anyone have any experience with this and can point me in the right direction?

+4
source share
1 answer

This can be done using aws-sdk gem.

Your task can be divided into two main steps: 1) create a temporary local file with your json data, 2) upload to S3. A very simple, procedural example:

require 'aws-sdk' # generate local file record = Record.find(1) file_name = "my-json-data-#{record.id}" local_file_path = "/tmp/#{file_name}" File.open(local_file_path, 'w') do |file| file.write(record.to_json) end # upload to S3 s3 = AWS::S3.new( :access_key_id => 'YOUR_ACCESS_KEY_ID', :secret_access_key => 'YOUR_SECRET_ACCESS_KEY') bucket = s3.buckets['my-s3-bucket-key'] object = bucket.objects[file_name] object.write(Pathname.new(local_file_path)) 

Refer to S3Object docs for more information.

+4
source

Source: https://habr.com/ru/post/1496943/


All Articles