2

I'd like to setup a simple Sinatra app up to capture the raw POST data that gets sent to the the / URL and save this data to the file system as a file with the format YYYYMMDD-HHMMSS.json.

The data I will be posting to the URL with be simple text data in the JSON format.

What is the best way to set this simple Sinatra app up? Unsure how to capture the raw POST data.

UPDATE / Code:

post '/' do
    raw = request.env["rack.input"].read
    n = DateTime.now
    filename = n.strftime("%Y%m%d") + "T" + n.strftime("%H%M%S") #any way to include microseconds?
    # write to file
end
BuddyJoe
  • 69,735
  • 114
  • 291
  • 466
  • See answer below and comments. I have tried every method mentioned in the comments on this page http://www.gittr.com/index.php/archive/getting-data-into-a-sinatra-application/ – BuddyJoe May 17 '11 at 01:07
  • None of those methods worked. How do I troubleshoot this? – BuddyJoe May 17 '11 at 01:07

1 Answers1

5

Something like this should work for you:

post "/" do
  File.open("#{Time.now.strftime("%Y%m%d-%H%M%S")}.json", "w") do |f| 
    f.puts params["data"]    
  end 
end
intellidiot
  • 11,108
  • 4
  • 34
  • 41
  • Wow. Got to it while I was tweaking the question. That should do the trick. Any way to include the milliseconds in the timestamp? – BuddyJoe May 16 '11 at 18:49
  • 1
    `Time.now.strftime("%Y%m%d-%H%M%S%L")` with the milliseconds. – Vasiliy Ermolovich May 16 '11 at 19:15
  • Had to upgrade to 1.92 on Windows to get this. 1.87 on Windows missing the %L option. Was driving me batty. – BuddyJoe May 16 '11 at 19:51
  • hmmm. "data" and :data not working. How do you troubleshoot this? Do I need to send a certain request header for this to work? – BuddyJoe May 17 '11 at 00:17
  • Returning params.count. I get 0 – BuddyJoe May 17 '11 at 00:26
  • 3
    I used the following jQuery: `$.ajax({type: 'POST', url: '/', data: '{data: "someData"}'});` from firebug to test this snippet. – intellidiot May 17 '11 at 03:53
  • funny that exact same thing on my computer writes nothing to the file. I have also tried this via the Firefox REST Client extension. Does Sinatra auto-sniff the fact this is JSON coming in? Wonder if I missing some gem? I have upgraded like I said before to 1.92 on Windows – BuddyJoe May 17 '11 at 14:37
  • Chalking this up to my install of Ruby or Sinatra. Thanks. +1 and answer – BuddyJoe May 23 '11 at 15:07