Category Archives: JavaScript

Consider Turbolinks 5 for your next Rails project

Turbolinks 5 is a library for web applications that makes pages load faster. Here’s how:

  • When the user navigates, it replaces only the body of the page (and merges the headers) with AJAX, instead of doing a full page load
  • If the user navigates to a page that they’ve already viewed in that session, it displays a cached version and then checks for new content in the background

These features make your app appear at least 2x as fast to the user.

You could realize similar preformance benefits with a client-side app written in a JavaScript MVC that talks to the server through an API.

Turbolinks’ genius is that delivers the improved user experience of a client-driven app without you having to write a client-driven app.

Consider it, every time

You should strongly consider Turbolinks 5 for any new Rails project.

I didn’t consider previous versions of Turbolinks. Superficially, they seemed buggy. Turbolinks 5 is a full rewrite, and it’s been running swimmingly in production for Basecamp 3 and my little project, TourExec.

Why consider Turbolinks now?

Because your users deserve the fastest possible experience, and you deserve to ship quickly.

When I built TourExec, a tour booking platform, I wanted an excellent booking experience for customers. Simply, they choose a time and how many they are, and the app displays available times. Then, hopefully they click a time and book.

Booking a tour

Notice in the interaction there is no page reload. The user chooses a date, and the times dynamically update. When the user clicks a time, the booking form appears almost instantly.

This is driven by Turbolinks. I didn’t write any JavaScript to retrieve and display times based on the selected date. I only wired the list selectors to “refresh” the page when the user changed them. Turbolinks takes care of the rest, retrieving the new page body from the server and swapping it out.

This is the most advanced implementation of Turbolinks in my app. The rest of its benefits apply without any extra work.

My admin interface for businesses is super snappy, thanks to Turbolinks. At the point of sale with a line of customers waiting, a business benefits from a tour roster that loads in a third of the time.

Pairing Turbolinks with a JavaScript MVC

I pull in React for some particularly interactive features, like a schedule builder that lets businesses define their tour times. In that case, it was easier to write React components than figure out a server-driven approach that delivered an acceptable experience.

Too often, frameworks like React grow to take over an entire application without a true analysis of the pros and cons.

In the case of TourExec, Turbolinks delivers a speedy experience throughout, and I bring in React for particular needs. This balance allows us to move quickly and reduces technical debt down the road.

The trade-offs

Nothing is without a trade-off. Turbolinks won’t work effortlessly with every JavaScript plugin, but its developers have documented how to adapt, and I’ve found it very doable.

Retrieving RSS with JavaScript

I’ve open sourced RSS to API, which allows you to retrieve RSS feeds via JavaScript. With a few clicks, you can deploy it to Heroku and start consuming RSS from your JavaScript code!

Almost any site with an RSS fee returns a reverse-chronological list of items, each containing a title, link, and date. This consistency can be powerful. You can create a dashboard with the latest feed item(s) from multiple sites. You can bring your corporate web site’s news items on your intranet. The possibilities are limited only by what is available online.

In many cases, it makes sense to grab RSS feeds via JavaScript and display them in the browser. However, cross-domain restrictions generally prevent direct retrieval of feeds via JavaScript. The Google Feed API provided an easy way to retrieve feeds with JavaScript, but it was deprecated in April of 2015 and could disappear at any moment. Alternatives like the Feedly API do not accept requests directly from JavaScript.

To consume RSS in JavaScript, it’s necessary to route it through a server. Your JavaScript communicates with a server, which retrieves the feed and returns it. Google Feed API is going away, and it’s a pain to build your own, so I’m releasing RSS to API. It’s a lightweight Ruby app that accepts requests for feeds and implements caching to serve them quickly. With just a few clicks, you can deploy it onto Heroku’s free plan (you’ll want to up your plan to use this in production).

RSS to API has been tested with dozens of feeds on one page. See the example below, which might lag because Heroku’s free plan has to go to sleep once in a while.

See the Pen RSS to API Example by csm123 (@csm123) on CodePen.

Why React JS matters for developers

It can be tempting to think of React JS as just another JavaScript framework, along the lines of Angular JS and Ember JS. This entirely misses why it was created and the problems it solves.

React is not designed to solve problems specific to web applications. Rather, it is designed to solve problems for all applications.

This sounds like buzz until you look at where React is going. Its first uses were in web applications, specifically Facebook and Instagram. Now, though, it’s rapidly moving past that:

  1. Facebook used it to build a native iOS mobile app, and is open sourcing react-native to allow anyone to do the same for iOS and Android. Learn more from Facebook’s recent React conference: overview, deep dive.
  2. Flipboard used it to power canvas graphics on its web site, which unlike the traditional browser DOM can operate with video-like smoothness. They open sourced this add-on to React.
  3. Netflix uses it to create TV interfaces. Hear about it in their own words.
  4. It’s used on both the server-side and the client-side. React doesn’t need a web browser to work.

Why is React gaining traction on so many platforms, unlike other JavaScript frameworks?

It’s simple: React presents a better model for development, generally.

React’s impact is best explained by its side effects:

  1. Your code is clear. It is arranged into components, each with its own defined responsibility.  Learn more about structure.
  2. Your app is predictable. It’s very clear where data flows, and what happens when a user does something. Learn more about data flow.
  3. Your app is fast. React is really, really fast, creating a better experience for users, even if you have a ton of data. See this example.
  4. Your app is standards-based. React adds layers only when it needs to. You feel like you are actually writing JavaScript and HTML, not some magic template language.
  5. Surprise, you’re an app developer. React breaks down barriers across platforms, by applying its same model across the board. This means that once you learn the React way of structuring an web application, you have a huge head start on developing a native iOS or Android app, thanks to react-native. Surely this will happen to other platforms.

So, get to know React, even if you don’t see a need for it in your current projects. Far more than a shiny new JavaScript framework,  it could represent a new standard for structuring applications.

See also, the benefits of adding React to a real-world Rails app, and a deep dive into React in Rails.

Finally, check out the React JS Conf 2015 videos.

React JS and Flux in Rails, a complete example

I recently wrote about real-world results with React JS. Here is a concrete example of adding React to a Rails app, start to finish.

React JS is a library from Facebook that powers user interfaces. It is simpler, faster, and less opinionated than many JavaScript MVC frameworks, making it easier to bring into an existing app. Start by reviewing our recommended React resources, then check out an example below.

The example

At Cook Smarts, we want recipes to be consistent, so we provide administrators with suggested ingredient names. That way, a red bell pepper is always called a red bell pepper.

Suggestions are populated from previous recipes automatically, but they need to be pruned by an administrator to make sure they’re accurate.

The app needs to provide an Excel-like way to quickly prune suggestions.

React JS, in under 150 lines of readable code, gets us exactly what we need, an Excel-like data editor.

Editing ingredient suggestions

Tooling

The example below relies upon Ruby on Rails, the react-rails gem (latest stable version), and Fluxxor (added to the app’s JavaScript manifest).

Our server actions in Rails

A Rails controller provides JSON data to the view and processes edits and deletions to the database.

Our data model in Fluxxor

A typical React implementation includes a data model, or store, which manages data and the actions that can be taken on the data. At a Cook Smarts, we use Fluxxor,  inspired by Facebook’s Flux concept.

A JavaScript object holds our store and defines the actions that the store will take (renaming and deleting ingredients):

The object contains the store itself, instantiated through Fluxxor’s createStore method.

The object also contains the store’s actions, which communicates with the simple API we defined in the Rails controller:

Finally, the object includes a method for creating a Flux object containing the store and its actions. The Flux object is passed to the React-based UI in the next section.

Read more about Fluxxor and how it helps you easily define data models that play well with React. For more on the concept, check out Facebook’s Flux overview.

Our UI in React

So far, we have covered the server-side API and the client-side data store. We still need to build our client-side UI, and that’s where React comes in.

React apps are basically component trees. The ingredient suggestions editor contains multiple ingredient suggestions,, so our component tree at its simplest is:

  • IngredientSuggestionsEditor
    • IngredientSuggestion
    • IngredientSuggestion
    • IngredientSuggestion

The IngredientSuggestionsEditor component is the parent, and watches the Flux store for any changes (see code comments):

The component above renders an IngredientSuggestion component for each ingredient. The IngredientSuggestion component shows the name of the ingredient and allows the user to edit it (see code comments):

Tying it all together

All of the code above is in a global JavaScript function that we call from our Rails view.  That function spins everything up and renders the UI to the page. Global functions aren’t ideal, but Rails’ asset pipeline leaves us with few other options. While a bit inelegant, this approach works well in a Rails app.

The global function creates the Fluxxor store and renders React components to the page. Here is its code, excluding the snippets we’ve already covered:

The Rails view containing the suggestion editor runs the global function on page load, passing all the ingredient suggestions in JSON format, which we passed to the view from the Rails controller:

Here’s the full code for the Rails controller, Rails view, Fluxxor store/actions, and React components.

In the future it will only get easier to connect React and Rails, with a new 1.0 version of the React gem in the works. At Cook Smarts, we use the latest stable React gem and include Fluxxor in the app’s JavaScript manifest.

React allowed us to get a client-side interface up and running in a couple of hours.  React presents few surprises and operates consistently. It’s no wonder that it powers much of Facebook and Instagram, two sites that have to work for a wide array of users.

React JS and Rails – real-world results

There are many React JS intros out there, but too few articles about bringing React into an existing Rails app.

At Cook Smarts, we brought React JS into the core of our application, used by thousands of people each week. We moved quickly from the conceptual beauty of React to figuring out how to make it work 100% of the time.

Here’s what React JS delivered in just a bit of time:

  1. A bug-free user experience back to IE 7
  2. Speed, with no detectable latency on the client side
  3. Better structured JavaScript
  4. Thrilled users, who now have a more modern app experience
  5. Developer happiness (that’s me!)

First, some background. Cook Smarts is a service that helps people plan their weekly at-home meals. It suggests meals for the week, and the user can choose which ones to make, add meals from other weeks, adjust serving sizes, and adjust for dietary restrictions.

This is a lot of user interaction. A month ago, users selected which meals to make through a vanilla form. We then generated a static grocery list and meal plan. If they wanted to make any changes, they had to submit the form all over again.

Screen Shot 2014-12-29 at 6.30.05 PM

Screen Shot 2014-12-29 at 6.31.14 PM

It worked, but it needed improvement. Users wanted the app to remember their choices and allow them to check items off the grocery list. They wanted to make their selections as they browsed, not all at once.

We chose React JS because it is un-opinionated and friendly to existing apps. We could drop React into particular parts of the app without changing any other parts.

After implementing React, the meal planning experience is this simple, with no forms:

CookSmartsMealPlanning

React is based on components that you arrange in a tree that basically documents itself. Here are the basic components for grocery list page:

  • GroceryListContainer
    • GroceryListItems
      • GroceryListItem

… and for the menu page:

  • DaysContainer
    • Day
      • DayTitle
      • DayVersion
      • DayServings

With React, you code each component separately, in a mix of JavaScript and HTML called JSX. Your component code contains the layout and behavior of that component, and React makes everything happen on the client.

React has minimal impact on your Rails app’s overall structure, making it easy to bring into an existing app. Here were the basic steps to implementing it:

  1. Add react-rails to your gemfile
  2. Create a directory in app/assets/javascript called “components” and create your components there as .JSX files
  3. Reference your new components in your views
  4. Create the server-side API’s necessary to feed and interact with your React components (this is not React-specific, just something an app needs to do as it implements more client-side functionality)

I presented to a local meetup about the process of implementing React for Cook Smarts, and hope to put together a how-to soon. In the mean time, check out these great resources for incorporating React and Rails:

Feel free to tweet me with any questions!

Update: See a full example of adding React to a Rails app