Daniel Doubrovkine bio photo

Daniel Doubrovkine

aka dB., @awscloud, former CTO @artsy, +@vestris, NYC

Email Twitter LinkedIn Github Strava
Creative Commons License

I love reflection, especially the Ruby kind. JavaScript reflection, though, can exhibit interesting runtime behavior.

I needed to do something for a given object type, so I wanted to get the name of an object’s type in JavaScript. StackOverflow has a few good discussions on this topic here and here. I wrote this innocent piece of CoffeeScript last week.

if item.constructor.name == "Spline"
  alert("Reticulated spline: #{item.reticulated}");

It worked great in my dev environment and in tests, but failed in staging and would have failed in production had we not noticed. I put in a debugger and, surprise, item.constructor.name was “d”. WTF? Turned out, this was caused by the fact that we produced minified JavaScript during asset packaging. All functions and class names were replaced by single character names.

Because item was a Backbone model, the solution was to introduce modelName into it and check that.

class App.Models.Spline extends Backbone.Model
  modelName: "Spline"

If you’re minifying JavaScript, make sure to turn this on in tests and catch similar bugs early. We use Jammit, so this is done by setting package_assets to always in assets.yml (setting it to on in tests has no effect).