Viet
Viet

Reputation: 3387

Exporting static JSON data to Amazon S3 and retrieving it through AJAX

On my Rails 3 application, I would like to export static JSON data to an Amazon S3 bucket, which can be later retrieved and parsed by an AJAX call from said application.

The JSON will be generated from the app's database.

My design requirements probably will only need something like a rake task to initiate the export to S3. Every time the rake task is initiated, it'll overwrite the files. Preferably the file name will correspond to the ID number of the record where the JSON data is generated from.

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

Upvotes: 4

Views: 3946

Answers (1)

rossta
rossta

Reputation: 11494

This can be accomplished with the aws-sdk gem.

Your task could be broken into two basic steps: 1) generate a temporary local file with your json data, 2) upload to S3. A very basic, procedural example of this:

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))

Check out the S3Object docs for more info.

Upvotes: 7

Related Questions