<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alex Rothenberg on Medium]]></title>
        <description><![CDATA[Stories by Alex Rothenberg on Medium]]></description>
        <link>https://medium.com/@alex_36920?source=rss-a969f0ab5529------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_K0oU6NLJS-Fu3pc.</url>
            <title>Stories by Alex Rothenberg on Medium</title>
            <link>https://medium.com/@alex_36920?source=rss-a969f0ab5529------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 10:29:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alex_36920/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Using Capabilities to Secure our APIs]]></title>
            <link>https://medium.com/@alex_36920/using-capabilities-to-secure-our-apis-8e234cb2846a?source=rss-a969f0ab5529------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e234cb2846a</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Alex Rothenberg]]></dc:creator>
            <pubDate>Tue, 04 Jun 2019 14:49:33 GMT</pubDate>
            <atom:updated>2019-06-04T14:49:33.979Z</atom:updated>
            <content:encoded><![CDATA[<p>At <a href="https://www.iorahealth.com/">Iora Health</a> we are on a mission to transform healthcare, starting with primary care. Part of that transformation is powered by our home-grown collaborative care platform, which we affectionately refer to as <a href="https://www.iorahealth.com/why-we-built-chirp/">Chirp</a>. Chirp contains all of our patients’ medical records, so our Engineering team works hard to keep those records secure.</p><p>Today I’m going to share some of the techniques we use to ensure that our Chirp APIs only reveal appropriate information to whoever’s asking. We follow software industry best practices such as<a href="https://en.wikipedia.org/wiki/HITRUST"> HITRUST</a>,<a href="https://aws.amazon.com/architecture/well-architected/"> AWS Well Architected</a>, and<a href="https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/REST_Security_Cheat_Sheet.md"> OWASP</a>, but we have to make sure we’re implementing those principles correctly.</p><p>We think about securing our APIs and web pages as three steps that happen before allowing the business logic of the request to run.</p><ol><li><strong>Authentication</strong> — Who are you?</li><li><strong>Authorization</strong> — Are you allowed to do this action?</li><li><strong>Scoping</strong> — Are you allowed to do it to that patient or that note?</li></ol><p>The rest of this article will talk through each of the steps, showing how they are each involved in every request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/0*IW2ctkowN2LAzvSF" /><figcaption>Every Chirp Request Authenticates, Authorizes, and Scopes access</figcaption></figure><h3>Authentication</h3><p>In contrast to many web applications, there’s nothing about a patient’s medical chart that an anonymous user (or the Google crawler) needs to access. Chirp contains a wide set of features, from measurements and vitals to chart notes to population health dashboards. Some of these features are intended for both patients and staff members; others are used primarily by our staff members or internal operations teams.</p><p>We secure every one of our APIs using OAuth so we know who is making each request and can prevent anyone who isn’t an authorized user from getting in the front door.</p><p>Most of our services are written in Rails so there’s a before_action we put in front of each request as a gate to start the authentication process. If the request includes an access_token we confirm it’s validity with our OAuth provider and proceed. Otherwise, we redirect them to the login page or, if it’s an API request, return a 401 Unauthorized. Our OAuth response gives us some information about who is making the request so that no request can make it through until we know the identity of the requester.</p><h3>Authorization</h3><p>Once we know who the user is, we need to decide whether the user is allowed to perform the requested action. For example, <em>view a patient’s note</em> can be done by a patient or one of our practice users, while <em>sign a patient’s note</em> is limited to only licensed medical providers.</p><p>Our first attempt to implement this used<a href="https://github.com/varvet/pundit"> Pundit</a> to build policy classes that granted access to each controller action — <em>note index</em>, <em>note show</em>, <em>note update</em>, etc. Pretty quickly we started to get overwhelmed and realized we were being forced into too granular a level to understand or even think about the rules we were building. We’re running many services, each of which exposes a bunch of endpoints, so doing the math convinced us it wouldn’t work.</p><pre>many ✕ a bunch = ouch my brain hurts</pre><p>It was a problem not being able to reason about concepts like <em>sign a note</em> which requires access to <em>note show</em>, <em>patient show</em>, <em>note sign</em> and many other actions. We decided this type of concept was important, and as with many abstractions, once we identified and named it things got much easier. We decided to call these things capabilities. A capability is a set of actions that defines business functionality we want to assign a group of users — for example, <em>view a practice schedule</em>, <em>view a patient</em>, <em>update a patient </em>or <em>sign a note</em>. Each capability combines access to several API endpoints, potentially across different services; access can be granted to different groups such as <em>patients</em>, <em>practice staff</em>, <em>licensed providers</em>, even <em>providers in Colorado</em>. There were few enough capabilities that once we started talking about them we were able to reason about Chirp as a whole and gain new insights into how our system should work. We’re still using Pundit for scoping and we’ll talk about that when we get to the next section.</p><p>Let’s look at how we use capabilities to check authorization.</p><p>First we enhanced our OAuth provider to lookup and return the current user’s capabilities as part of its authentication response. We are able to make these changes because we built our own OAuth provider called Snowflake, since every person is as unique as a snowflake. Snowflake now manages the mapping between our capabilities and users. For example Dr. Dog has the <em>sign a note</em> capability while Alex does not. Right now it does this through a few database tables but eventually we hope to integrate this with our IT and HR systems and the existing groups maintained there. Now the authentication response includes the user’s capabilities and looks something like this:</p><pre>{<br>  user: {<br>    uid: &quot;1234567890&quot;,<br>    first_name: &quot;doctor&quot;,<br>    last_name: &quot;dog&quot;,<br>    email: &quot;doctor_dog@iorahealth.com&quot;,<br>    capabilities: [&quot;sign-a-note&quot;, &quot;view-patient&quot;]<br>  }<br>}</pre><p>Once we know the current user’s capabilities we enhanced our before_action by adding an authorize step. This step can now check whether the current action is included in one of the user’s capabilities. We’re storing the list of capabilities granted to each service in code because that list typically only changes when we make a code change and we wanted these rules to be governed by version control and code review. The configuration looks like this:</p><pre>config.capability_rules = {<br>  view_a_patient: [<br>    { controller: &quot;api/v1/patient&quot;, action: &quot;show&quot; },<br>    ...<br>  ]</pre><pre>  sign_a_note: [<br>    { controller: &quot;api/v1/patient&quot;, action: &quot;show&quot; },<br>    { controller: &quot;api/v1/notes&quot;, action: &quot;show&quot; },<br>    { controller: &quot;api/v1/notes&quot;, action: &quot;sign&quot; },<br>    ...<br>  ],</pre><pre>...<br>}</pre><p>Distributing this responsibility to each of our services is working out well for us so far.</p><h3>Scoping</h3><p>The last step in securing our APIs is to make sure that users can only interact with <em>their</em> patients. We went back to using Pundit for this since <a href="https://github.com/varvet/pundit#scopes">Pundit scopes</a> do exactly that: Instead of querying against everything in our database, we are limited to the subset the current user is allowed to see. It essentially puts a where onto your query in addition to whatever other ActiveRecord goodness you’re doing. For example, in our NotesController show action we want to ensure that the note with the requested id belongs to a patient you’re allowed to see — so we write:</p><pre>def show<br>  my_notes = policy_scope(Note)<br>  note = my_notes.find(params[:id])<br>  ...<br>end</pre><p>This has to be written in each action, and because it’s so important not to forget any, Pundit provides a nice after_action called verify_policy_scoped, which verifies that at least one policy_scope was called. We’ve added that to our base ApplicationController like so:</p><pre>class ApplicationController &lt; ActionController::Base<br>  after_action :verify_policy_scoped<br>end</pre><p>Most of the Pundit documentation suggests this is useful for read actions like index and show but we’ve found it useful to use everywhere including creates where there is no id parameter. In these cases we verify the foreign keys on the request to make sure the note we create belongs to one of the user’s patients. We write our create action something like:</p><pre>def create<br>  my_patients = policy_scope(Patient)<br>  patient = my_patients.find(params[:patient_id])<br>  ...<br>  Note.create(patient: patient, ...)<br>end</pre><p>As we started writing scopes we realized almost all of them scoped in the same way:</p><ol><li>Practice staff members are scoped within their practice</li><li>Patients are scoped to themselves only</li><li>Applications and jobs can operate across all our data</li></ol><p>Pundit made it pretty simple to <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a> this up by building a base policy that defined a scope encoding those three rules.</p><pre>class IoraPolicy<br>  class Scope<br>    attr_reader :user, :scope</pre><pre>    def initialize(user, scope)<br>      @user = user<br>      @scope = scope<br>    end</pre><pre>    def resolve<br>      if policy_user.practice_user?  <br>        scope.by_practice_id(policy_user.practice_id)<br>      elsif policy_user.patient?<br>        scope.by_patient_id(policy_user.patient_id)<br>      elsif policy_user.iora_application_user?<br>        scope<br>      else<br>        scope.none <br>      end<br>    end<br>  end<br>end</pre><p>When applying a scope, Pundit uses a naming convention to find a policy. For example, when asking for policy_scope(Note) Pundit will look for the policy NotePolicy. This means we’ve needed to create a bunch of empty policies that inherit from IoraPolicy.</p><pre>class NotePolicy &lt; IoraPolicy<br>end</pre><p>It is a bit tedious to create these nearly empty files but the advantage is that in the rare cases where we need to scope differently than the standard rules we have a convenient place to define our custom rules. For instance, if we want to allow admin practice users to view all practices but leave the default rules in effect for everyone else, we could define a PracticePolicy like this:</p><pre>class PracticePolicy &lt; IoraPolicy<br>  class Scope &lt; Scope<br>    def resolve<br>      if policy_user.practice_user? &amp;&amp; admin?<br>        scope # unscoped to everything <br>      else<br>        super<br>      end<br>    end<br>  end<br>end</pre><p>You may have noticed our IoraPolicy calling scope.by_practice_id and scope.by_patient_id. scope is usually the ActiveRecord model we’re limiting (i.e., Note) which means we need to add self.by_practice_id and self.by_patient_id methods to any model we’re scoping (which turns out to be most our models). Most of our models have practice_id or patient_id as foreign keys so these are easy to write as single line where method. When that doesn’t work we can write more complex joins or logic to achieve the scoping since these are just methods.</p><pre>class Note &lt; ActiveRecord::Base<br>  def self.by_patient_id(practice_id)<br>    where(patient_id: patient_id)<br>  end</pre><pre>  def self.by_practice_id(practice_id)<br>    joins(:patient).<br>      merge(Patient.where(practice_id: practice_id))<br>  end<br>end</pre><h3>Summary</h3><p>Every request in Chirp authenticates with our OAuth provider, authorizes with our capabilities, and scopes data access using Pundit scopes, thus ensuring that only the right people can do the right things to the right data.</p><p>Portions of this architecture have been in place for a long time but until recently we also had ad-hoc implementations scattered throughout. All of the engineers on the Chirp team have contributed to transitioning to this more-consistent capabilities system over the course of nine months.</p><p>We’re really happy to have this uniform solution in place. Now that we’ve named capabilities we’ve begun talking about securing different aspects of Chirp in ways we never did before. We’re building out a new capability to allow our compliance team to correct signed notes when incorrect information was added by mistake. We’re also trying to figure out how to think about the <em>prescribe a drug</em> capability, which is trickier than it seems, because a provider may be licensed in one state but not another, so the capability changes depending on which patient the provider is seeing.</p><p>We’re excited to see where this leads.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e234cb2846a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rewriting our Core Backbone App in Ember While Developing at Full Speed]]></title>
            <link>https://medium.com/@alex_36920/rewriting-our-core-backbone-app-in-ember-while-developing-at-full-speed-412b50d3c89b?source=rss-a969f0ab5529------2</link>
            <guid isPermaLink="false">https://medium.com/p/412b50d3c89b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ember]]></category>
            <dc:creator><![CDATA[Alex Rothenberg]]></dc:creator>
            <pubDate>Wed, 22 Mar 2017 15:10:58 GMT</pubDate>
            <atom:updated>2017-03-22T15:10:58.186Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*9W8fDRHoHmq9ojhzzDsYSQ.jpeg" /></figure><p>Our nearly 6 year old Backbone application is showing its age — but how can we change frameworks without stopping the world? In this article we’ll talk about how we’re doing just that: replacing the old Backbone app with a new shiny Ember app while we develop new features and keep everything running so we can continue to treat patients every day.</p><p>At <a href="http://www.iorahealth.com/">Iora Health</a> our business is primary care and our care teams use “Chirp”, the electronic medical records platform we’ve built, while seeing patients all day. We’re also a modern engineering team and are continuously making Chirp better. Chirp is designed to be enjoyable for our care teams and single page apps have helped us immensely. Unfortunately it’s been tougher and slower to make changes. Incremental refactors within Backbone weren’t going to be enough.</p><h4>Our Ground Rules</h4><p>We’ve all been a part of big bang rewrites and know those are never fun (and rarely successful). We gave ourselves some ground rules:</p><ol><li>Continue developing new features during the rewrite</li><li>Release the changes incrementally as we go — no big bang release</li><li>End up with an application architecture similar to what we would have come up with if we had started it as a greenfield project</li></ol><h3>Our Mental Model</h3><p>It’s been helpful for us to think of this super simplified model of how single page apps work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*79RBYj-OCa38V1t-i32FMw.png" /><figcaption>Super Simplified SPA Architecture</figcaption></figure><p>This is overly simplistic but it has helped us think about how we can swap out the framework one step at a time. Also, we’re using it to make sure we’re moving towards an end state that isn’t too far off from where a greenfield Ember project would end up.</p><h3>Past Attempts</h3><p>Using our simplified model, we can describe our existing Backbone application as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*JnWnoXC5KJm0EOUxSsXT0A.png" /><figcaption>Architecture of current Chirp Application using Backbone</figcaption></figure><p>Backbone.js was truly innovative and absolutely the right tool for us to use in 2011. At the time, the alternatives were no frontend code or creating a spaghetti mess of jQuery — we’re tremendously grateful to Jeremy Ashkenas (<a href="https://twitter.com/jashkenas">@jashkenas</a>) for creating it. Over the years we wound up building our own custom framework on top of Backbone and realized that wasn’t where we should be spending our time. We’ve experimented with a few approaches to bringing our app up to date before this current effort.</p><p><strong>Backbone Marionette </strong>— We replaced our ad-hoc framework with Backbone Marionette. This worked but the effort stalled out with a portion of Chirp rewritten and we never had the appetite to tackle the rest of the application. We probably abandoned the effort because we felt the JavaScript community had moved beyond Backbone.</p><p><strong>React Components </strong>— We tried working our way up from the bottom by writing our views as React components hosted inside of a Backbone view within the existing application. This worked well but only addressed the view layer. Even though we were happier to write React components, we never quite managed to eliminate the Backbone models or router, so this effort stalled out too.</p><h3>The Ember Rewrite</h3><p>With Ember we decided to approach the rewrite from the top-down: replacing the router first, then the models and leaving the views for last.</p><p>In order to be incremental and ship to production early and often, we’ve broken our effort into 3 phases:</p><ol><li>Create an Ember app that’s responsible for routing while leaving the Backbone models and views in place.</li><li>Replace Backbone models with Ember Data models one route at a time, hydrating the existing Backbone models to pass into the existing views.</li><li>Rewrite one view at a time using Handlebars and eliminating all Backbone from that view.</li></ol><h3>Ember Phase I</h3><p>At the end of Phase I our architecture will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*BrnyrAExQwXbgtn0g1PIVg.png" /><figcaption>Phase I Architecture using Ember Router with Backbone Models and Views</figcaption></figure><p>We’ve got an Ember application, Ember router and Ember routes playing nicely with the Backbone models and Backbone views.</p><p>Let’s get into the details and show some code! We’ll look at a page that shows a patient’s lab results for lab. When a patient’s blood work comes back from the lab we get the results from our external partners in a scary HL7 format out of the 1980’s and massage it into a reasonable JSON format. We then create a page with the patient’s lab results. The URL looks like /facesheet/123456789/labs/12 looking at lab 12 for patient 123456789.</p><h4>Creating an Ember App</h4><p>The first step was to create a new Ember-CLI app. This made us feel like we were off to a good start since we were using the same tool as any greenfield app. Ember-CLI does so much for us! The only tricky part was making sure the Backbone objects we’d want to use during this transition were available from Ember. The problem was solved by adding a few lines to our ember-cli-build.js to include the files from our legacy Backbone app in the Ember build.</p><pre>// ember-cli-build.js</pre><pre>[<br>  &#39;javascripts/vendor.js&#39;,<br>  &#39;javascripts/application.js&#39;,<br>  &#39;javascripts/templates.js&#39;,<br>  &#39;stylesheets/application.css&#39;<br>].forEach((file) =&gt; {<br>  app.import(`../public/assets/${file}`, { type: &#39;test&#39; });<br>});</pre><h4>Creating Ember Routes to Replace our Backbone Routes</h4><p>We recreated our Backbone routes using the Ember router. Luckily our existing Backbone routes fit pretty smoothly into the Ember nested route pattern so this was mostly a syntax change.</p><p>From the Backbone routing</p><pre>routes: {<br>  &quot;:patient_guid&quot;: &quot;facesheet&quot;,<br>  &quot;:patient_guid/labs&quot;: &quot;lab&quot;,<br>  &quot;:patient_guid/labs/:labId&quot;: &quot;lab&quot;<br>}</pre><p>To the Ember routing</p><pre>// router.js<br>AppRouter.map(function() {<br>  this.route(&#39;facesheet&#39;, { path: &#39;:patientGuid&#39; }, function() {<br>    this.route(&#39;labs&#39;, function() {<br>      this.route(&#39;show&#39;, { path: &#39;/:labId&#39; }, function() {<br>     });<br>    });<br>  });<br>});</pre><h4>Loading Backbone Models in an Ember Route</h4><p>In order to do our rewrite incrementally and ship quickly, we needed to load our Backbone models inside our Ember routes. Luckily, the Ember model hook isn’t tied to Ember Data. It doesn’t care what it loads and waits for any returned promise to resolve before continuing on. Backbone models use promises so we can ask these legacy models to load their data and proceed. This is still a regular Ember route.</p><pre>// routes/facesheet/lab/show.js<br>export default Ember.Route.extend({<br>  async model({ labId }) {<br>    const lab = new Iora.Models.Lab({ id: labId });<br>    await lab.fetch();<br>    return lab;<br>  }<br>});</pre><p>In this example, we load the Backbone model from a global Iora.Models.Lab with the param labId. We wrote Chirp before import was widely available, so we stored our objects in globals and referred to them that way.</p><p>You may be wondering where the .then’s are in the code above. We’ve recently discovered the magic of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function">async and await</a>, which lets us treat promises synchronously and make everything much simpler to read. In this example, the async before the model hook means it is a function that returns a promise and the await lab.fetch() inside the function calls a promise, but synchronously waits for the promise to resolve before moving on to the next line return lab;. Someday this will be supported by browsers but for now it exists as a Babel polyfill. It’s kinda fun to view the transpiled source and see the crazy code the polyfill produces to make asynchronous promises appear synchronous or you can take it on faith that it works ¯\_(ツ)_/¯.</p><h4>Handlebars Template</h4><p>Our Handlebars template for this route is pretty simple. We load a component, passing along the Backbone model we loaded in the route.</p><pre>// templates/facesheet/lab/show.hbs<br>&lt;section class=&quot;facesheet-content&quot;&gt;<br>  {{lab-show lab=model}}<br>&lt;/section&gt;</pre><p>On to the lab-show component.</p><h4>Creating an Ember Component that Renders a Backbone View</h4><p>This is another place where we integrate Ember with Backbone in order to more quickly get to production. The lab-show component doesn’t render itself the Ember way. In fact, it’s Handlebars template is empty. Instead, it renders a Backbone view into the area of the DOM Ember gives it using this.$() — similar to how components that use jquery widgets work.</p><pre>// components/lab-show.js <br>export default Ember.Component.extend({<br>  didRender() {    <br>    this._super(...arguments);</pre><pre>    const backboneView = new Iora.Views.Labs.Show({<br>      lab: this.get(&#39;lab&#39;)<br>    });<br>    this.set(&#39;_backboneView&#39;, backboneView);<br>    backboneView.setElement(this.$());<br>    backboneView.render();<br>  },</pre><pre>  willDestroyElement() {<br>    this._super(...arguments);<br>    const backboneView = this.get(&#39;_backboneView&#39;);<br>    if (backboneView) {<br>      backboneView.leave();<br>      this.set(&#39;_backboneView&#39;, null);<br>    }<br>  }<br>});</pre><p>After Ember updates the DOM using the Handlebars template it calls didRender, so that’s where we need to intervene. We create our Iora.Views.Labs.Show Backbone view while passing in the lab model instance and saving it in a property for cleanup. Then, we tell the view it lives on this component’s portion of the DOM. Finally, we ask the view to render itself.</p><p>To avoid memory leaks, we need to do some cleanup when the component is destroyed. Using the willDestroyElement hook, we retrieve the previously-saved Backbone view and call the cleanup hooks on it, assuming they exist to remove the view’s associated event bindings and such.</p><h4>Will It Blend?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*ysnIxCa7Gr-sE5YjtZffjA.gif" /></figure><p>So far we have created an Ember application, added some routes, loaded our Backbone models and created an Ember component that renders our Backbone view. Are we there yet?</p><p>We can visit /facesheet/123456789/labs/12 and see our lab page — hooray! However, our care teams don’t just read the pages, they interact with them and clicking links doesn’t work — boo!</p><p>Not to worry! We’ll get over this final hurdle with one last step.</p><h4>Dealing with Legacy Hash-Based URLs</h4><p>When we created the Backbone app, pushState was not yet widely supported so we used hash-based URLs. The links inside of the Backbone views are created using the hash-based approach, which are broken in our bright new pushState-based Ember world. When we click a link to lab 13 our URL now looks like /facesheet/123456789/labs/12#facesheet/123456789/labs/12 and that’s not right!</p><p>We don’t want to open up our Backbone code and make lots of changes to every link. Instead, we came up with an instance initializer to intercept location changes, convert the hash-based URLs to our new form asking the Ember router to do its thing.</p><pre>// instance-initializers/backbone-route-interceptor.js<br>export function initialize(appInstance) {<br>  const router = appInstance.lookup(&#39;router:main&#39;);<br>  const hashLocation = appInstance.lookup(&#39;location:hash&#39;);</pre><pre>  hashLocation.onUpdateURL((url)=&gt; {<br>    const BACKBONE_URL_PREFIX = &#39;/#facesheet/&#39;;<br>    if (url.startsWith(BACKBONE_URL_PREFIX)) {<br>      const restOfUrl = url.substr(2);<br>      const newUrl = `/${restOfUrl}`;<br>      router.replaceWith(newUrl);<br>    }<br>  });<br>}</pre><pre>export default {<br>  name: &#39;backbone-route-interceptor&#39;,<br>  initialize<br>};</pre><p>This code gets loaded once on Ember startup. It looks a bit complicated so let’s walk through it. First it loads the Ember router and saves it in a variable for use later when the URL changes. Then we use Ember’s <a href="http://emberjs.com/api/classes/Ember.Location.html#toc_hashlocation">HashLocation</a> to monitor for changes to the URL hash and invoke our callback function. Inside this callback we check that the hash URL is one of our facesheet URLs. When matching, we remove the # and tell the Ember router to take us to the transformed URL.</p><p>With this in place we can test it out loading our page /facesheet/123456789/labs/12, seeing lab 12, then clicking a link to lab 13 being redirected to /facesheet/123456789/labs/13 and seeing lab 13. It all works!</p><h3>What We’ve Learned So Far</h3><p>We’ve been pleasantly surprised with how straightforward our rewrite has been so far. We’re following our ground rules and achieving our aims:</p><ol><li><em>Continue developing new features during the rewrite</em><br>We have two development teams and while one team has been working on this the other has been developing new pages and changing existing ones in Backbone without having to worry about the Ember changes.</li><li><em>Release the changes incrementally as we go — no big bang release</em><br>After about 6 weeks our users are all on the Ember app and our Backbone router has been deleted. We released individual routes as soon as they were completed. However the performance cost of reinitializing the Ember app each time the user left and returned was too high so we didn’t turn it on until all the routes done. We did do a mini-big bang release for Phase I, but we think we’ll be able to be truly incremental and avoid that for the coming phases replacing the Backbone models and views.</li><li><em>End up with an application architecture similar to what we would have come up with if we had started as a greenfield project</em><br>We seem to be heading towards a clean Ember-CLI app even though we do have some temporary code to enable Ember and Backbone to interact. This has been essential in allowing us to release early and often. We are confident that will go away as we replace the remaining Backbone code with Ember.</li></ol><h4>Our Test Suite Saved our Bacon</h4><p>We’re in the process of entirely rewriting our application which is big and scary. How can we know we didn’t break anything? We can’t click every link to make sure it works. Ah, but actually we can! Over the years we’ve invested in an extensive acceptance test suite that we’re now running against the new Ember application. It’s paying off big time!</p><p>It has caught a few edge cases we missed in our migration that we were able to quickly fix. Most importantly, its given us a high level of confidence that our new, evolving application works correctly. The only bug that has been reported in production was a button we intentionally removed because we thought it was unused. Once our users let us know they depended on it we were able to quickly add it back.</p><h4>We’ve Gotten Speed for Free</h4><p>We’ve been very pleasantly surprised by the huge performance improvement when changing routes. This is because of the model caching Ember provides for free. Even though we’re still using Backbone models not Ember Data when we switch from one lab to another in facesheet/labs/show the only model hook that re-fires is the show one. The ancestor facesheet and labs routes that load the patient and a summary of all labs are unchanged. We certainly could have built better caching into our old Backbone app, but that would have taken thought and work. Who wants to spend time worrying about that! A big advantage of Ember is that the framework has already thought of issues like this, so we don’t have to. It’s hard to argue with getting something like caching for free.</p><p>We haven’t gotten much direct feedback from our users about the site being faster (even though we know it it is 😀). Instead, we have gotten complaints about other areas we haven’t touched being slower, which we’re interpreting as indirect feedback that the facesheet is faster.</p><h3>Next Steps</h3><p>We’ve completed Phase I of our rewrite and its been live in production for a few weeks with no reported issues. We’re embarking on Phase II to use Ember Data models to talk to our API followed by Phase III to convert our Backbone views to Ember components using Handlebars. We’re very happy with our current progress and can see the path toward ending up with a pure Ember app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*Jmw-Tnmg_47d-8Q0SxZr7A.png" /><figcaption>The Ember Architecture end state</figcaption></figure><p>We’ll post follow-ups as we move through the other phases of this rewrite.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=412b50d3c89b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>