Receiving posted JSON with Sinatra

small tricks to make things easier

Published July 27, 2015 #ruby #sinatra #toys

Here’s some simple code to accept a JSON string posted to a Sinatra end point rather than a form. I switched from using jQueries $.ajax method to superagent as part of my exploration of the node javascript package universe, and it has a different way of serializing nest objects when posting as a form. Specifically, it doesn’t.

I needed something that could do both.

Code to use form encoding or JSON blob

This first tries and loads the parameters using the normal form encoding methods. If it doesn’t find the path parameter, it attempts to parse the body’s payload, found in request.body.read, using JSON.parse:

  post '/post' do
    payload = params
    payload = JSON.parse(request.body.read).symbolize_keys unless params[:path]

    logger.info "Saving #{payload[:path]} with #{payload[:meta]}"

    file = load_app.sitemap.find_resource_by_path payload[:path]
  end

Javascript

The coffeescript that calls this is:

request.post "/api/post"
  .set('Content-Type', 'application/json')
  .send path: @state.path, meta: @state.metadata, body: @state.markdown
  .end (err, response) =>
    if response.ok
      @state.saving = false
      @state.dirty = false
      @trigger @state

In this case, @state.metadata is also a complex object, and posting it as JSON ensures that it’s marshalled correctly.

Not too complicated.

Read next

See also

How to track your coworkers

Simple passive network surveillance

How much information do you bleed? Ever wonder who is else is using your network? Or,who has actually showed up at the office? Networking primer The simplest thing we can do to make this work is to check to see which devices have registered themselves on the network. As devices come and go, they connect automatically, so we will have a pretty good idea if people are there or not.

Read more

Adding search to a middleman blog

slightly simplier than google

We’re going to build a simple, niave search for middleman blogs. We’re going to build a search index at build time, and then use that index to perform the search itself on the client side. Building the index When you typed in something in google, it doesn’t then go and hit every page on the internet to check to see if there’s a match. It doesn’t even look at every page that it has squirreled away somewhere in the googleplex.

Read more

OSX Script for Kiosk Mode

make your own screen saver

In the office, we run Jenkins on the same machine that we run Benevolent Gaze. During iOS builds, the iOS simulator will take over the screen for the build, and then leave the beautiful screen on the desktop, hiding our smiling faces. We want to return to Safari in this case, but we also want to make sure that if someone is actually in front of the machine it will let them do their thing.

Read more