Friday, December 20, 2013

Turn a Rails controller into a Single Page Application

Single Page Apps are becoming more popular. When you see them in practice (GMail, Twitter, Facebook), it's quite cool. Then you look at your current project and you see how impossible it is to make it a Single Page App. Who's going to pay for that? It sounds like months of work, just replacing the whole existing functionality.

The thing is, it doesn't need to be the whole project at once. It's not all or nothing. You can make multiple small SPAs.

Where to start?

Look at your current Rails views/controller. Is there a clear widget, like a search bar, that could be extracted? That's a good candidate.

There's also another approach. Usually when you have a typical CRUD controller, it's always the same group of views. There's a list of things, that you can see, edit, update, add new items, etc.

Such controller is a good candidate for a SPA.

You end up with one view (index), which loads the JS. After the JavaScripts are initialised, an AJAX GET request is made to /index.json. This retrieves all the data for the list. Apart from that you need an API endpoint for creating, updating and deleting. Note that you don't need an endpoint for new/edit. They become JavaScript views, but they don't need to exist on the server-side. 

You turn the existing Rails views into handlebars templates (or whatever that renders the HTML client-side). They get rendered at appropriate moments by the JavaScript code.

If you prefer, you can use a framework for that. You can also do it on your own, as it's very easy. We usually go the hexagonaljs way - manual, with a nice structure and typical adapters: serverSide and guiAdapter. 

What does it give you?
  • Single Page Apps are architecturally better solutions than Rails views
    • it's easier to test
    • once you learn it, it's quite easy to write
    • there's strong decoupling between your frontend and the backend
    • the backend is simpler
    • the resulting SPA has less 'features' than a Rails view
      • by default, no URL for each 'view', just for the main one
        • good enough for most cases
      • for SEO you need to do additional work on the backend
        • not always needed
It doesn't need to be all or nothing

You can test the water by choosing some parts of your project and turn them into JavaScript apps. We're in the process of doing that in a large Rails project - I think, we're now with about 15 small Single Page Apps. We keep adding new features, it doesn't slow us down. Thanks to the faster build (it's easier to test decoupled components rather than a monolith), we're actually saving time.

No comments: