<?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"><channel><title><![CDATA[Alex Speller]]></title><description><![CDATA[Alex Speller]]></description><link>http://alexspeller.com/</link><generator>Ghost v0.4.2</generator><lastBuildDate>Sun, 15 Mar 2026 08:14:17 GMT</lastBuildDate><atom:link href="http://alexspeller.com/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Loading and Error Substates in Ember]]></title><description><![CDATA[<p>Loading an error substates in ember can be confusing - here's what I found when I investigated them in depth:</p>

<div>  
<iframe src='https://player.vimeo.com/video/157235004'  style="position: absolute; left: 0; top: 0; right: 0; bottom: 0; width: 100% !important; height: 100% !important;" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>  
</div>]]></description><link>http://alexspeller.com/loading-and-error-substates-in-ember/</link><guid isPermaLink="false">27927b99-c1e9-4662-b37b-2531b1d61963</guid><dc:creator><![CDATA[Alex Speller]]></dc:creator><pubDate>Fri, 01 Apr 2016 15:00:17 GMT</pubDate></item><item><title><![CDATA[EmberCamp London Talk - Routing]]></title><description><![CDATA[<p>This is my talk at EmberCamp London about routing in Ember. I talk about route nesting and UI nesting, when to use renderTemplate and when not to. If you have any doubts about how route structuring works in ember, I hope this talk will help make things clearer.</p>

<iframe width="854" height="480" src='https://www.youtube.com/embed/Dp57YdJPWx4'  frameborder="0" allowfullscreen></iframe>

<p>And in case you're curious, this is how the spotlight looked in practice :)</p>

<p><img src='https://alexspeller.com/content/images/2015/Nov/alexspeller.jpg'  alt="graph" /></p>]]></description><link>http://alexspeller.com/embercamp-london-talk-routing/</link><guid isPermaLink="false">4f5251d7-3748-4e39-b1e7-f951ecc33c27</guid><dc:creator><![CDATA[Alex Speller]]></dc:creator><pubDate>Wed, 25 Nov 2015 16:17:22 GMT</pubDate></item><item><title><![CDATA[Javascript components and Ember]]></title><description><![CDATA[<p>Often when using Ember, it's tempting to integrate external javascript components. Sometimes this is trivial and easy, but often it can be both difficult and counterproductive. Here I will try to explain the pros, cons and reasoning behind them.</p>

<h2 id="whenitmakessenseselfcontainedcomponents">When it makes sense: self-contained components.</h2>

<p>When using external components, you have to decide whether the external component has responsibility for managing the DOM or ember does. If the responsibility can be handed off entirely to the external component, it can be a good choice. For example, imagine a calendar popup component that is a jquery plugin, triggered with this imaginary api:</p>

<pre><code class="js">var calendar = $(someElement).calendar({  
  onChange: function(date) {
    alert(date);
  }
});

calendar.setDate(new Date());  
</code></pre>

<p>In this case, the internals of the calendar are opaque and we don't want Ember to manage any of the dom. This can be trivially wrapped in an ember component like so:</p>

<pre><code class="js">App.SomeCalendarComponent = Em.Component.extend({  
  currentDate: null,
  initCalendar: (function() {
    var _this = this;
    // this.$() returns a jQuery object scoped to the component's DOM element
    this.calendar = this.$().calendar({
      onChange: function(date) {
        _this.set('currentDate', date);
      }
    });
  }).on('didInsertElement'),

  updateCalendarDate: (function() {
    // the date changed elsewhere, so update the displayed date
    this.calendar.setDate(this.get('currentDate'));
  }).observes('currentDate')
});
</code></pre>

<p>This component can now be easily used in your templates like so, binding the date property to a variable of your choosing:</p>

<pre><code class="hbs">{{some-calendar currentDate=someVariable}}
</code></pre>

<p>EvilTrout has <a href='http://eviltrout.com/2014/06/03/jquery-component.html' >a great tutorial</a> that goes into this in more detail.</p>

<h3 id="butcanyoudobetter">But can you do better?</h3>

<p>Maybe. There are two cases when the above may not be the best approach.</p>

<ol>
<li>Has someone already made an ember specific version of what you want? For example, <a href='http://emberui.com/documentation/calendar' >http://emberui.com/documentation/calendar</a>. This can both save you hassle and maintenance and integrate better out of the box, including better variable binding and runloop integration.  </li>
<li>Do you need lots of customization? Ember provides massively powerful tools for building complex UIs. If you want something that you can customise to your precise specifications, then rolling your own will probably pay off long term.</li>
</ol>

<h2 id="whenitveryrarelymakessensecomponentsthatwrapalotofdom">When it very rarely makes sense: components that wrap a lot of DOM.</h2>

<p>For example, a modal component. Treating external components as a "black box" is quite trivial to integrate. However if you want your component to have DOM managed by Ember inside of it you will almost always regret trying to shoehorn external libraries into this role. The reason for this is that there is now an unclear seperation of concerns between which library is responsible for which part of the DOM. You need to manually keep track of the rendering flow of e.g.</p>

<pre>
  Ember renders container
    → Plugin renders modal container and animates
      → Ember renders modal contents
</pre>

<p>The reverse must be handled for teardown, and it can get very complex when trying to square the expectations of the external library with the expectations of the ember runloop and rendering process. Whilst it can be done, and is sometimes unavoidable, in my experience you will almost always write less, and simpler code just using ember's built in powertools to build what you need, rather than trying to bash something into shape to work in this role.</p>

<p>In addition, for the major use-cases there are often pre-built ember-specific components that will be easier to adapt for your use case than trying to make the non-ember library do what you need. This is doubly the case as soon as you have very specific custom requirements for your UX interactions - customising ember specific code will make your life a lot easier, give you more flexibility, and take less time in the long run.</p>

<p>Two examples of common components that are relevant to this discussion are:</p>

<ul>
<li><a href='http://instructure.github.io/ic-tabs' >ic-tabs</a> for tabbed navigation</li>
<li><a href='http://instructure.github.io/ic-modal/' >ic-modal</a> for modal dialogs</li>
</ul>

<p>In short, I would argue that rolling your own components often corresponds to the red line on this graph, whist non-ember components corresponds to the blue line:</p>

<p><img src='http://www.briankeng.com/wp-content/uploads/2015/07/main-qimg-becd53fa321a6a527ea6fc1072635e17-300x236.png'  alt="graph" /></p>

<p>[1] <a href='https://www.quora.com/What-are-the-most-profound-life-lessons-from-Stanford-Professor-John-Ousterhout?share=1' >https://www.quora.com/What-are-the-most-profound-life-lessons-from-Stanford-Professor-John-Ousterhout?share=1</a></p>]]></description><link>http://alexspeller.com/javascript-components-and-ember/</link><guid isPermaLink="false">6d190dcd-7d00-4fbb-8878-52e59cd5dc0c</guid><dc:creator><![CDATA[Alex Speller]]></dc:creator><pubDate>Tue, 09 Dec 2014 16:36:25 GMT</pubDate></item><item><title><![CDATA[A gentle introduction to music theory (in ruby)]]></title><description><![CDATA[<p>Music theory can seem arcane and unapproachable. But underneath the weird names and symbols, the basics are actually pretty simple.</p>

<p>The real issue is that the documentation is bad and the API is worse! In this talk I will show how to start with nothing but a ruby interpreter, and generate sine waves, notes, scales, modes, chords, arpeggios and songs, in a way that will be understandable to those who have never touched an instrument before and will (hopefully) offer an interesting new perspective even to those who are already well versed in music theory.</p>

<iframe src='https://player.vimeo.com/video/161193523'  width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>]]></description><link>http://alexspeller.com/a-gentle-introduction-to-music-theory-in-ruby/</link><guid isPermaLink="false">7ef62448-aca5-452a-934e-a5aaf5e822c0</guid><dc:creator><![CDATA[Alex Speller]]></dc:creator><pubDate>Mon, 11 Aug 2014 11:00:00 GMT</pubDate></item><item><title><![CDATA[Server Side Validations with Ember Data and DS.Errors]]></title><description><![CDATA[<p>Validation errors are an unfortunate fact of life that you will have to deal with in almost every non trivial application. Often you will want to do client-side validations, and for that I recommend having a look at <a href='https://github.com/dockyard/ember-validations' >Ember Validations</a>.</p>

<p>However, client side validations can be complex to implement, and you will always need to do server side validations anyway, both because you can't trust anything done on the client side, and some validations like uniqueness can't be implemented correctly without the transactional semantics only available on the server side.</p>

<p>It's a lot easier to start out doing server-side only validations, and this post shows how to take advantage of Ember's built in error handling.</p>

<p><strong><em>Shameless plug:</strong> This post explains some techniques that are used in Emberkit, my Ember/Rails SaaS kit. If you find this post useful, have a look, as you'll find many more useful techniques demonstrated there:</em></p>

<p><em><a href='https://emberkit.com/' >https://emberkit.com</a></em></p>

<h2 id="startingoutwithaform">Starting out with a form</h2>

<p>I'm going to start out with a basic form, using the form components I build in <a href='http://alexspeller.com/simple-forms-with-ember/' >my previous post</a> - if there's anything in this post that's not making sense you might want to read that one first.</p>

<iframe width="100%" height="300" src='http://jsfiddle.net/L96Mb/11/embedded/result,js,html'  allowfullscreen="allowfullscreen" frameborder="0"></iframe>

<p>A you can see, nothing works yet. If you click on the Save button, you will get an error in the console:</p>

<pre><code class="text">Error: The backend rejected the commit because it was invalid: {name: must be present, email: Is not an email,Is blank, base: This person is a generally unsavoury character and is not allowed to sign up}  
</code></pre>

<p>I'm going to be using <a href='https://github.com/appendto/jquery-mockjax' >mockjax</a> to emulate the response needed from your server, which should have a response code of <code>422 Unprocessable Entity</code>, and a body that looks like this:</p>

<pre><code class="json">{
  "errors": {
    "field_one": ["error 1", "error 2"],
    "field_two": ["error 1"]
  }
}
</code></pre>

<h2 id="introtodserrors">Intro to DS.Errors</h2>

<p>So how do we get ember to handle the errors more gracefully? It turns out that all we need to do is to handle the  <code>save()</code> promise rejection, by providing a function as the second argument to the <code>then</code> handler:</p>

<pre><code class="coffeescript">model.save().then -&gt;  
  alert 'saved'
, -&gt;
  #empty function
</code></pre>

<p>Just by providing that empty function, the error is considered handled and no console error is thrown. Your model also gets it's <code>errors</code> property populated with an instance of <code>DS.Errors</code>, which you can find out more about <a href='http://emberjs.com/api/data/classes/DS.Errors.html' >in the API docs</a>.</p>

<p>For now, we're just going to use the <code>length</code> property to see if there are any validation errors and display a message to the user:</p>

<iframe width="100%" height="300" src='http://jsfiddle.net/L96Mb/5/embedded/result,js,html'  allowfullscreen="allowfullscreen" frameborder="0"></iframe>

<h2 id="usingformcomponentstodisplayerrors">Using form components to display errors</h2>

<p>So now we have an error message, but it's quite useless because we're not telling the user what errors actually occurred. To improve this a bit, I'm going to extend the form components from <a href='http://alexspeller.com/simple-forms-with-ember/' >my previous post</a> to show the errors on each field, along with in the alert above the form:</p>

<iframe width="100%" height="300" src='http://jsfiddle.net/L96Mb/7/embedded/result,js,html'  allowfullscreen="allowfullscreen" frameborder="0"></iframe>

<p>The key parts here are:</p>

<ul>
<li>Extend App.FormFieldComponent to know what errors are on each field so inline messages can be shown:</li>
</ul>

<pre><code class="coffeescript">hasError: (-&gt;  
  @get('object.errors')?.has @get('for')
).property 'object.errors.[]'

errors: (-&gt;  
  return Em.A() unless @get('object.errors')
  @get('object.errors').errorsFor(@get('for')).mapBy('message').join(', ')
).property 'object.errors.[]'
</code></pre>

<ul>
<li>Create a new <code>error-messages</code> component to display the error messages nicely</li>
<li>Add a <code>titleize</code> helper to convert <code>"form_field"</code> to <code>"Form field"</code>, so that you can display the error messages in human-readable form.</li>
<li>Use the new component in the template to display the errors.</li>
</ul>

<h2 id="handlingarbitraryerrors">Handling arbitrary errors</h2>

<p>If you've been paying very close attention, you may have noticed that we have a problem - not all error messages we returned are displayed!</p>

<p>The reason for this is that DS.Errors is currently only populated for attributes that you have defined on your model with <code>DS.attr</code> (or <code>DS.belongsTo</code> / <code>DS.hasMany</code>). But we have returned an error for <code>base</code> in our (fake) json response. Currently it is just ignored. It's quite easy to hack around this, by changing how errors are applied to your models:</p>

<pre><code class="coffeescript">DS.Model.reopen  
  adapterDidInvalidate: (errors) -&gt;
    recordErrors = @get 'errors'
    for own key, errorValue of errors
      recordErrors.add key, errorValue
</code></pre>

<p>In this example, you can return arbitrary errors and they will be displayed in the alert above the form. I also add special handling for an error called <code>base</code>, allowing you to have errors that don't apply to a specific field but the whole record in general:</p>

<iframe width="100%" height="300" src='http://jsfiddle.net/L96Mb/9/embedded/result,js,html'  allowfullscreen="allowfullscreen" frameborder="0"></iframe>

<p>I currently have a <a href='https://github.com/emberjs/data/pull/1984' >pull request open</a> in ember data to make this the default behaviour - hopefully it will be merged and you won't have to worry about this in the future.</p>

<h2 id="handlingerrorswiththerestadapter">Handling Errors with the RESTAdapter</h2>

<p>All the previous examples use <code>DS.ActiveModelAdapter</code>. However many ember applications use <code>DS.RESTAdapter</code>, which doesn't include this error handling by default. If you are using the <code>RESTAdapter</code>, you can add support for automatic error handling like this:</p>

<pre><code class="coffeescript">App.ApplicationAdapter = DS.RESTAdapter.extend  
  ajaxError: (jqXHR) -&gt;
    error = @_super(jqXHR)

    if jqXHR and jqXHR.status is 422
      response = Ember.$.parseJSON(jqXHR.responseText)
      errors = {}
      if response.errors?
        jsonErrors = response.errors
        Ember.keys(jsonErrors).forEach (key) -&gt;
          errors[Ember.String.camelize(key)] = jsonErrors[key]

      new DS.InvalidError(errors)
    else
      error
</code></pre>

<iframe width="100%" height="300" src='http://jsfiddle.net/L96Mb/10/embedded/result,js,html'  allowfullscreen="allowfullscreen" frameborder="0"></iframe>

<h2 id="bonusgeneratingthecorrectresponsesinrails">Bonus: Generating the correct responses in Rails</h2>

<p>The format of the json required is quite simple, you shouldn't have any problems generating it in any backend language. However, if you happen to be using Rails on the backend, it's really easy to generate this automatically. If you already have validations on your model, you can just render the errors object to get the exact format you need:</p>

<pre><code class="ruby">def create  
  user = User.new sanitized_user_params
  if user.save
    render json: user
  else
    render json: {errors: user.errors}, status: 422
  end
end  
</code></pre>

<p>In fact, it can be even easier than this, because the respond_with helper will do just that automatically:</p>

<pre><code class="ruby">def create  
  user = User.create sanitized_user_params
  respond_with user
end  
</code></pre>

<p>Now you have implemented server-side validations, have a look at <a href='https://github.com/dockyard/ember-validations' >Ember Validations</a> to see how you can add client side validations that can validate your form on the client side in real-time, for a better UX for your visitors.</p>]]></description><link>http://alexspeller.com/server-side-validations-with-ember-data-and-ds-errors/</link><guid isPermaLink="false">ea68634d-5722-49e9-ba68-f6c893eec7c0</guid><dc:creator><![CDATA[Alex Speller]]></dc:creator><pubDate>Sat, 02 Aug 2014 16:40:51 GMT</pubDate></item><item><title><![CDATA[Awesome Ember.js Form Components]]></title><description><![CDATA[<p>A common ember pattern is a form that edits properties of an object. In this post I will show how to use nested components and dynamic bindings to produce concise forms in your templates with automatic <code>&lt;label&gt;</code> tags, bootstrap compatibility, and a very clean api.</p>

<p><strong><em>Shameless plug:</strong> This post builds a simplified example of the forms that are used in <a href='https://emberkit.com/' >Emberkit</a>, my Ember/Rails SaaS kit. If you find this post useful, have a look, as you'll find many more useful techniques demonstrated there:</em></p>

<p><em><a href='https://emberkit.com/' >https://emberkit.com</a></em></p>

<h2 id="startingout">Starting out</h2>

<p>Let's start out with a basic form implemented using built–in ember primitives:</p>

<iframe width="100%" height="500" src='https://jsfiddle.net/alexspeller/pfQuh/embedded/html,js,result'  allowfullscreen="allowfullscreen" frameborder="0"></iframe>

<p>This is much like a normal HTML form. One thing that may be different to how you would usually use buttons in ember is that the button itself is a plain <code>&lt;button type="submit"&gt;</code> with no Ember code whatsoever, and the <code>{{action "updateUser" on="submit"}}</code> helper is attached to the form tag.</p>

<p>This ensures that the form can be submitted both by clicking on the button, and by pressing "Enter" when one of the fields is focussed. It's important to preserve the UX that your users are used to and forms that don't submit properly with the usual keyboard interactions can be particularly frustrating.</p>

<h2 id="introducingacomponenttemplate">Introducing a component template</h2>

<p>This is a good start, and it works fine. However it's a bit verbose and repetitive. Each form input needs a lot of code to add a label and assign a unique ID so that the label is associated with the input. This is annoying and error-prone. Let's add in a component to reduce some of the duplication:</p>

<iframe width="100%" height="500" src='https://jsfiddle.net/alexspeller/53dNe/embedded/html,js,result'  allowfullscreen="allowfullscreen" frameborder="0"></iframe>

<p>This is already a big improvement. The code duplication is reduced and it's simpler to look at. However I'm not completely happy with the API, and currently there's the potential for a bug - the <code>form-field</code> component uses the label that you pass in as its ID. This is not ideal as IDs are supposed to be unique, and this component would only let you have one field with a given label on the page at a time.</p>

<h2 id="addingacomponentobject">Adding a component object</h2>

<p>Currently there's only a component template, but no object. Components can be template–only, object–only, or have both a template and an object. For an example of an object-only component, have a look at <a href='http://discuss.emberjs.com/t/bootstrap-active-links-and-lis/5018' >my discuss post about Bootstrap, active links and LIs</a>.</p>

<p>Let's add a component object and give it a smart default for the field type. It will default to "text" unless the label contains the string "password":</p>

<iframe width="100%" height="500" src='https://jsfiddle.net/alexspeller/tPZYR/3/embedded/js,html,result'  allowfullscreen="allowfullscreen" frameborder="0"></iframe>

<h2 id="nestingcomponents">Nesting components</h2>

<p>Of course, components can be nested. If we have lots of forms in our app, we probably want to make it simpler to write the surrounding form tag as well:</p>

<iframe width="100%" height="500" src='https://jsfiddle.net/alexspeller/rMQu5/2/embedded/html,js,result'  allowfullscreen="allowfullscreen" frameborder="0"></iframe>

<p>This is looking really good. Note the use of <code>sendAction</code> in <code>App.ObjectFormComponent</code> to send an action from the component that is otherwise isolated from the surrounding scope.</p>

<h2 id="addingsomemagic">Adding some magic</h2>

<p>Up to this point I don't think anything I've done is remotely controversial. However this next bit might be. Components are supposed to be isolated from their surrounding scope. However, I have found that it makes sense to break this isolation in the circumstance where you want to nest components and give them specific behaviour based on how they are nested. If you want to read more or have an opinion on this topic, have a look at <a href='http://discuss.emberjs.com/t/isolation-of-components-always-required/5036' >my discourse post</a>. For now,  to improve this api even further and also solve the id problem, I'll show an example of what component nesting and dynamic binding can do:</p>

<iframe width="100%" height="500" src='https://jsfiddle.net/alexspeller/XyCKJ/2/embedded/html,js,result'  allowfullscreen="allowfullscreen" frameborder="0"></iframe>

<p>There's quite a bit going on here so I'll break down the last changes one at a time.</p>

<p>The end result is that we now have a terser API for specifying form fields – <code>{{form-field for="name"}}</code> instead of <code>{{form-field label="Name" value=name}}</code> – and the form fields each have access to an <code>object</code> property, which is what is passed into the parent <code>object-form</code> component as the <code>for=this</code> argument. Remember that in a template {{this}} refers to the controller, which in this case is an ObjectController that proxies to the current User created in the model hook.</p>

<p>Having access to the object that the form refers to allows solving the ID problem mentioned earlier, by creating a field id that is composed of a guid unique to the object, and also the field name:</p>

<pre><code class="coffeescript">  fieldId: (-&gt;
    "#{Em.guidFor @get('object')}-input-#{@get('for')}"
  ).property 'object', 'for'
</code></pre>

<p>The most complex part of this final version is the dynamic binding setup:</p>

<pre><code class="coffeescript">  setupBindings: (-&gt;
    @binding?.disconnect @ # Disconnect old binding if present

    # Create a binding between the value property of the component,
    # and the correct field name on the model object.
    @binding = Em.Binding.from("object.#{@get 'for'}").to('value')

    # Activate the binding
    @binding.connect @

  ).on('init').observes 'for', 'object'

  # Ensure the bindings are cleaned up when the component is removed
  tearDownBindings: (-&gt;
    @binding?.disconnect @
  ).on 'willDestroyElement'
</code></pre>

<p>The reason this is necessary is to allow for passing in a string to the component in the template, and getting access to both that string, and the value of the property referred to by the string. Usually it would be one or the other. Because we have access to the "object" that the form is referring to, through an alias to the parent component (<code>object: Em.computed.alias 'parentView.for'</code>), we can use the string to create a binding to the correct property on the object.</p>

<p>First any existing dynamic binding is disconnected if it is present. Then a manual binding is created that connects the correct property on the form's object to a property called <code>value</code> on the <code>form-field</code> component, and then that binding is activated by calling the connect method. A little bit of binding magic can often help adding polish to APIs!</p>

<p>Finally, we destroy the binding when the component is removed from the DOM using the disconnect method.</p>

<h2 id="bonusoptionalblockcomponent">Bonus - Optional block component</h2>

<p>So there's one more feature of components that's not that often used but is really useful. Our <code>form-field</code> component only handles text or password inputs at the moment, but what if we want to handle more input types? Sure, we can keep adding more automatic behaviour (and in the version of this code I use, textareas are automatically handled as well). But you can never plan for everything. What if you want some custom input that you only use in one place in your app?</p>

<p>This is when an optional block will come in handy. The idea is to make the component behave differently depending on whether it's used in block form or inline form:</p>

<pre><code class="handlebars">Inline form - use default input field:

{{form-field for="email"}}


Block form - provide custom input but still use wrapper and label etc:

{{#form-field for="somethingElse"}}
  {{my-crazy-custom-custom-input-field value=somethingElse}}
{{/form-field}}
</code></pre>

<p>This is easy enough to achieve with <code>{{#if template}} {{yield}} {{/if}}</code> in your component's handlebars template. If a block was provided, the <code>template</code> property will be present. If no block is provided, it will be absent:</p>

<iframe width="100%" height="500" src='https://jsfiddle.net/alexspeller/GL6zz/1/embedded/html,js,result'  allowfullscreen="allowfullscreen" frameborder="0"></iframe>

<h2 id="wrapup">Wrapup</h2>

<p>Hopefully this has been a useful walk-through of some advanced uses of components. If you want a much more comprehensive form library that helps with building forms in ember, you might want to check out <a href='https://github.com/dockyard/ember-easyForm' >Ember EasyForm</a> which inspired the API demonstrated here.</p>]]></description><link>http://alexspeller.com/simple-forms-with-ember/</link><guid isPermaLink="false">d0075fa0-f2d1-4f18-a900-1085058ec33a</guid><dc:creator><![CDATA[Alex Speller]]></dc:creator><pubDate>Wed, 04 Jun 2014 00:11:45 GMT</pubDate></item><item><title><![CDATA[Debounced and Throttled Observers in Ember.js]]></title><description><![CDATA[<p>Often in complex ember apps you want to use debouncing and throttling, to avoid doing expensive processing or too many server requests. I had hacked together a solution for this with <a href='http://underscorejs.org/' >underscore</a>, but then I found out that Ember.js includes built in throttle and debounce functions. A few minutes later, I came up with these handy little helpers:</p>

<pre><code class="javascript">Ember.debouncedObserver = function(func, key, time) {  
    return Em.observer(function() {
        Em.run.debounce(this, func, time);
    }, key)
};

Ember.throttledObserver = function(func, key, time) {  
    return Em.observer(function() {
        Em.run.throttle(this, func, time);
    }, key)
};
</code></pre>

<p>Using them is easy, just wrap your observer function with them like this:</p>

<pre><code class="javascript">App.IndexController = Em.ArrayController.extend({  
    selectObserver: Ember.debouncedObserver(function() {
        this.set('debounceSelected', this.get('selectedValue.firstName'));
    }, 'selectedValue', 1000),

    selectObserver2: Ember.throttledObserver(function() {
        this.set('throttleSelected', this.get('selectedValue.firstName'));
    }, 'selectedValue', 1000)

});
</code></pre>

<p>If you are using coffeescript, these have a slightly nicer argument order and support multiple dependant keys:</p>

<pre><code class="coffeescript">Ember.debouncedObserver = (keys..., time, func) -&gt;  
  Em.observer -&gt;
    Em.run.debounce @, func, time
  , keys...

Ember.throttledObserver = (keys..., time, func) -&gt;  
  Em.observer -&gt;
    Em.run.throttle @, func, time
  , keys...
</code></pre>

<p>You need to decide whether throttling or debouncing is right for you. Ben Alman has a good <a href='http://benalman.com/projects/jquery-throttle-debounce-plugin/' >blog post</a> that goes into more detail.</p>

<p><a href='http://jsfiddle.net/NQKvy/75' >Here's a JSFiddle</a> showing the code in action.</p>]]></description><link>http://alexspeller.com/debounced-and-throttled-observers-in-ember-js/</link><guid isPermaLink="false">e38e7f8d-06d2-453f-aa5c-39adfa30fff3</guid><dc:creator><![CDATA[Alex Speller]]></dc:creator><pubDate>Fri, 09 Aug 2013 11:00:00 GMT</pubDate></item><item><title><![CDATA[Intelligent String Matching for all Universities in DBpedia]]></title><description><![CDATA[<p>When <a href='http://qsapp.com/' >Quicksilver</a> came out, it changed the way I used my computer. Although it's not as essential to me these days as it used to be, it's the first implementation of fuzzy string matching that I encountered and fell in love with, a feature that I now take completely for granted most of the time but couldn't live without. I wouldn't be surprised if the main reason <a href='http://macromates.com/' >TextMate</a> was so successful for so long was it's implementation of this algorithm for it's “Open file in project” dialog. In fact, the main reason I switched from TextMate to <a href='http://www.sublimetext.com/' >Sublime Text</a> is the brilliant use of this algorithm in its autocomplete UI.</p>

<p>If you haven't seen this in action before, the idea is incredibly simple but brilliant. Instead of simply searching for a substring in a list of items, the string you type is scored against each item in the list. If you simply type the full string, you will get a high score the same as a naaive search implementation. However if you type the first character of each word, e.g. “uoo” for “University of Oxford”, then that will be one of the top results. If this isn't making much sense, <a href='http://static.railstips.org/orderedlist/demos/quicksilverjs/jquery.html' >a live demo</a> might help.</p>

<h2 id="theproblemathand">The problem at hand</h2>

<p>So, now I need to provide a way to select from a large number of university names in a web application, it would be remiss of me not to give my users the same great user experience of this search algorithm. In fact, it is an especially appropriate use case because universities are frequently referred to by abbreviations, for example UCL instead of University College London. If you just tested if the name contained the search string, a user typing “ucl” would get no results, however with the right fuzzy matching algorithm University College London will be the first result.</p>

<p>I started off by using <a href='https://github.com/rmm5t/liquidmetal' >LiquidMetal</a>, which has been working brilliantly for the roughly 300 universities in our database. Late last week, I discovered the number of organisations is about to rise to 15,000 - surely this approach simply won't be able to scale to that number of strings, and we'll have to revert back to simple string matching, perhaps even on the server to keep clients responsive?</p>

<h2 id="timetobreakoutthebenchmarks">Time to break out the benchmarks</h2>

<p>First I needed a large list of university names. <a href='http://dbpedia.org/' >DBpedia</a> to the rescue! I used the following query to get me a nice list of 15639 university names, which was perfectly serendipitous.</p>

<pre><code>PREFIX dbo: &lt;http://dbpedia.org/ontology/&gt;

SELECT DISTINCT ?name WHERE {  
     ?university rdf:type dbo:University.
     ?university dbpprop:name ?name
}
ORDER BY ?university  
</code></pre>

<p>Then I scoured the interwebs looking for various implementations of this fuzzy matching algorithm, and set up some benchmarking code. I wanted to rank all of the strings against a set of likely queries, hopefully some of which would be pathological, i.e. “This string is definitely not in the dataset at all and is also quite long”. I also compared against more simple matching using <code>String#indexOf</code> and <code>String#match</code>.</p>

<table class="out">  
<thead>  
  <tr><th>Algorithm</th><th>uoo</th><th>uoc</th><th title="uocam">uo…</th><th title="cambridge">ca…</th><th title="oxford">ox…</th><th title="University of Oxford">Un…</th><th title="university">un…</th><th title="University">Un…</th><th title="xxxy">xx…</th><th title="yyyx">yy…</th><th title="This string is definitely not in the dataset at all and is also quite long">Th…</th><th>Mean</th><th>Max</th></tr>
</thead>  
<tbody><tr><th><a href='http://static.railstips.org/orderedlist/demos/quicksilverjs/javascripts/quicksilver.js' >quicksilver.js</a></th><td class="number">67</td><td class="number">61</td><td class="number">67</td><td class="number">78</td><td class="number">50</td><td class="number">55</td><td class="number">53</td><td class="number">43</td><td class="number">35</td><td class="number">35</td><td class="number">68</td><td class="number">55.64</td><td class="number">78</td></tr><tr><th><a href='https://github.com/rmm5t/liquidmetal' >LiquidMetal</a></th><td class="number">71</td><td class="number">60</td><td class="number">61</td><td class="number">47</td><td class="number">39</td><td class="number">196</td><td class="number">144</td><td class="number">142</td><td class="number">6</td><td class="number">20</td><td class="number">17</td><td class="number">73.00</td><td class="number">196</td></tr><tr><th><a href='https://github.com/joshaven/string_score' >string_score.js</a></th><td class="number">72</td><td class="number">74</td><td class="number">68</td><td class="number">51</td><td class="number">44</td><td class="number">89</td><td class="number">63</td><td class="number">61</td><td class="number">20</td><td class="number">31</td><td class="number">40</td><td class="number">55.73</td><td class="number">89</td></tr><tr><th>String#indexOf</th><td class="number">2</td><td class="number">3</td><td class="number">3</td><td class="number">3</td><td class="number">3</td><td class="number">2</td><td class="number">3</td><td class="number">3</td><td class="number">2</td><td class="number">2</td><td class="number">2</td><td class="number">2.55</td><td class="number">3</td></tr><tr><th>String#match</th><td class="number">11</td><td class="number">12</td><td class="number">11</td><td class="number">13</td><td class="number">12</td><td class="number">14</td><td class="number">13</td><td class="number">13</td><td class="number">11</td><td class="number">11</td><td class="number">26</td><td class="number">13.36</td><td class="number">26</td></tr></tbody></table>

<div class="caption">All times in milliseconds. Hover over the strings in the header row to see the full string tested  
</div>

<h2 id="conclusions">Conclusions</h2>

<p>It turns out that the times are pretty fast even for the intelligent scoring algorithms. LiquidMetal seems to be vulnerable to a few pathological cases but the difference isn't really that big. I think from these results I will be using string_score.js, due to the more advanced featureset and better matching it provides.</p>

<p>I was really struck by how short these times are though - less than 100 milliseconds to rank 16,000 strings? Amazing. Even more amazing is the average of less than 3 milliseconds for the fastest method, with a simple indexOf. This suggests that even for a far larger dataset, searching on the client side should be relatively responsive and probably limited by memory more than anything else, even if you do have to sacrifice the fuzzy matching.</p>]]></description><link>http://alexspeller.com/intelligent-string-matching-for-all-universities-in-dbpedia/</link><guid isPermaLink="false">ce24391d-aad4-4099-9c51-0075e562c4ae</guid><dc:creator><![CDATA[Alex Speller]]></dc:creator><pubDate>Sun, 24 Feb 2013 12:00:00 GMT</pubDate></item><item><title><![CDATA[Source maps for coffeescript in Rails]]></title><description><![CDATA[<p>I've been following the progress on the new coffeescript compiler, mainly because the one minor issue I have with coffeescript is debugging in the browser. When I discovered that the latest version of the CoffeeScriptRedux compiler is now spitting them out, I figured I'd hack something together to see how it looks in a rails app.</p>

<p>Instructions to get this working with rails 3.2 and Chrome Canary:</p>

<ol>
<li>Follow <a href='http://ryanflorence.com/2012/coffeescript-source-maps/' >Ryan Florence's</a> instructions to get a build of coffeescript in your path that can create source maps  </li>
<li>Put the code below in <code>config/initializers/source_maps.rb</code>  </li>
<li>Run <code>rake tmp:cache:clear</code> and restart your server. Perhaps several times for luck.  </li>
<li>Fix any errors the new compiler gives about your scripts. It has a great one, <code>indentation error</code>, with no line number. Try <a href='http://uxmovement.com/wp-content/uploads/2013/02/pagination-scrolling.png' >coffeelint</a> if you're having problems as it will show any indentation errors.  </li>
<li>Get a taste of the future! An example would be to use console.log('hello world') in your coffeescript file. You will see that on the right of the log line in the web inspector, the link will point to a coffee file! Click the link, and the correct line is highlighted in the source view above.</li>
</ol>

<p><img src='http://alexspeller.com/content/images/2014/May/coffeescript-rails-screenshot.png'  alt="Console screenshot" /></p>

<p><strong>Important Note:</strong> this rather brutal hack replaces the normal coffeescript compiler by shelling out to the CoffeeScriptRedux compiler, which is not in fact finished. This is just a proof of concept, you probably shouldn't use it.</p>

<h1 id="thecode">The Code</h1>

<p><a href='https://gist.github.com/alexspeller/3730452' >View as gist</a></p>

<pre><code class="ruby"># config/initializers/source_maps.rb

if Rails.env.development?  
  require 'open3'
  module CoffeeScript
    class SourceMapError &lt; StandardError; end;

    class &lt;&lt; self

      def map_dir
        return @map_dir if @map_dir
        # Make the directory the maps are served from
        @map_dir = Rails.root.join("public/source_maps")
        @map_dir.mkpath
        @map_dir
      end

      def check_coffeescript_version
        version = `coffee --version`

        unless version.match(/(\d+)\.\d+\./)[1].to_i &gt;= 2
          raise "You must have coffeescript version 2.0.0-dev or higher to use source maps - see http://ryanflorence.com/2012/coffeescript-source-maps/"
        end
      end


      def compile script, options
        script = script.read if script.respond_to?(:read)

        if options.key?(:no_wrap) and !options.key?(:bare)
          options[:bare] = options[:no_wrap]
        else
          options[:bare] = false
        end

        check_coffeescript_version
        compile_with_source_map script, options
      end

      def compile_with_source_map script, options
        flags = %w(--js)
        flags &lt;&lt; "--bare" if options[:bare]

        javascript, stderr, status = Open3.capture3("coffee #{flags.join(' ')}", stdin_data: script)

        raise SourceMapError, stderr unless status.success?

        source_map_comment = generate_source_map options[:pathname], script if options[:pathname]

        return javascript &lt;&lt; source_map_comment

      rescue SourceMapError =&gt; e
        message = e.message.lines.first.chomp.gsub('"', '\"')
        relative_path_name = options[:pathname].to_s.gsub(Rails.root.to_s, '') if options[:pathname]
        relative_path_name ||= '&lt;unknown path&gt;'
        %Q{throw Error("Coffeescript compile error: #{relative_path_name}: #{message}")}
      end


      def generate_source_map pathname, script
        basename    = pathname.basename('.coffee')
        coffee_file = map_dir.join("#{basename}.coffee")
        coffee_file.open('w') {|f| f.puts script }


        # This command actually generates the source map, and saves it to a file
        source_map, status = nil
        Dir.chdir Rails.root.join('public/source_maps').to_s do
          source_map, stderr, status = Open3.capture3("coffee --source-map -i #{pathname.basename}")
        end

        raise SourceMapError, "Error while generating source map for file #{pathname}: #{stderr}" unless status.success?

        # I couldn't figure out how to control the 'file' and 'sources' values in the output,
        # so parse the map to JSON and rewrite these to ones that will work here
        data = JSON.parse(source_map)
        data['file'] = pathname.basename.to_s.gsub(/\.coffee/, '')
        data['sources'] = [pathname.basename.to_s]


        map_file = map_dir.join "#{basename}.map"
        map_file.open('w') { |f| f.puts data.to_json }
        Rails.logger.info "Compiled source map #{map_file}"

        return "\n//@ sourceMappingURL=/source_maps/#{map_file.basename}\n"
      end

    end
  end



  # Monkeypatch this method to include the scripts' pathname
  require 'tilt/template'

  module Tilt
    class CoffeeScriptTemplate &lt; Template
      def evaluate(scope, locals, &amp;block)
        @output ||= CoffeeScript.compile(data, options.merge(pathname: scope.pathname))
      end
    end
  end
end  
</code></pre>]]></description><link>http://alexspeller.com/source-maps-for-coffeescript-in-rails/</link><guid isPermaLink="false">539b5409-e517-4539-8531-f43240ff771a</guid><dc:creator><![CDATA[Alex Speller]]></dc:creator><pubDate>Sat, 15 Sep 2012 11:00:00 GMT</pubDate></item><item><title><![CDATA[Building a company in 42 days with 40 dollars]]></title><description><![CDATA[<h2 id="introduction">Introduction</h2>

<p>I worked on <a href='http://www.devtest.net/' >DevTest</a> on a total of 42 seperate days, over a period of around 6 months. This was all in my spare time during evenings and weekends, with the exception of a week of vacation to finish everything up and finally launch. And the only money I've spent so far has been $40 on hosting charges. A lot of those 42 days I only did a small amount of work; I think that if I'd been working on it full time, without taking long breaks between pieces of work, I'd have been able to do it in 2 months.</p>

<p>In this series of blog posts I'm going to explain some tips and tricks I used to make this possible. A large part of being able to pull off a feat like this is experience and practice, and having been programming for around 20 years in one form or another has made me able to get things done quickly, and a sense of what will work and what won't. But here I will try to share some of that knowledge and hopefully some will be useful for others.</p>

<h2 id="microagile">Micro agile</h2>

<p>In the past I've worked almost entirely in agile development environments with a focus on SCRUM. I'm wouldn't say I'm a "true agile believer", but it's a good tool to know and understand. For this project, I've been using what I call micro-agile. It's based on SCRUM development but cuts out almost everything because it's irrelevant when you're working solo. Doing this has helped me to keep focussed and stick the minimum viable product.</p>

<h3 id="trello">Trello</h3>

<p>I've used <a href='http://trello.com/' >Trello</a> to manage my todo list, it's amazing and free and above all <em>simple</em>. Before finding this tool I'd have said anything more than a pen and paper was overkill. Pen and paper is still fine, but Trello is simple enough to not get in the way and slightly more convenient than carrying around your list everywhere with you.</p>

<h3 id="planningasprint">Planning a sprint</h3>

<p>You should have one "product backlog" board. Use this as a dumping ground for new ideas. I had three columns, "Essential", "Post Launch" and "Inbox". New ideas go into the inbox. Simple.</p>

<p><img src='http://alexspeller.com/content/images/2014/May/trello-backlog.jpg'  alt="Product backlog example" /></p>

<p><em>Example product backlog</em></p>

<p>Now you need to plan your first sprint, this is what you'll need to do every 2 weeks or so:</p>

<ol>
<li>Brain dump into the inbox. Just put every little thing you can think of in there.  </li>
<li>Sort into Essential and Post Launch.  </li>
<li>Prioritize the "Essential" column by what's most important.  </li>
<li>Create a new board for your first sprint, with these columns: "Sprint backlog", "Specced", "In progress", "Done". Call this board "Sprint 1"  </li>
<li>Move an item from the top of the prioritized "Essential" column into the "Sprint Backlog" column of your sprint 1 board column. Repeat until you've got as much work as you think can be done in 2 weeks.</li>
</ol>

<p><img src='http://alexspeller.com/content/images/2014/May/trello-sprint.jpg'  alt="Sprint board example" /></p>

<p><em>Example sprint board</em></p>

<h3 id="executingasprint">Executing a sprint</h3>

<p>Now you have a prioritized, realistic list of tasks that you can plug on with one by one. Recall you have 4 columns on your sprint board, "Sprint backlog", "Specced", "In progress", "Done". At the moment everything should be in the backlog column. Now it's time to spec it out. Add a checklist to the first card in your sprint backlog, and try to flesh it out in more detail. Here's an example of a checklist for the candidate login feature:</p>

<p><img src='http://alexspeller.com/content/images/2014/May/micro-agile-requirements.jpg'  alt="Requirements example" /></p>

<p>You can move that card into the "Specced" column when you're happy with the requirements. You should try to think of all the requirements for this part up front, although this isn't always possible. The idea is that once you've specced an item, actually building it is just automatically following a list of checkboxes.</p>

<p>Not rocket surgery right? It's just common sense. But it really helps to have a simple process. One of the problems I find as a developer is that I easily get distracted and procrastinate. Having a mechanical process to get myself back on track when I've lost focus is essential.</p>

<h3 id="standups">Standups</h3>

<p>Standups in a full size development team are great for getting everyone on track. I found I missed this on my own, so I faked it. Whenever I had a block of time to work on DevTest, I'd start by looking at the current sprint board, and doing it in a different location I was working, and looking at what the next task to do was. Usually this would be downstairs in my living room. I'd do this until I got excited about building the next feature and couldn't wait to get programming, and found this helped again with motivation.</p>

<h2 id="whatnottobuild">What not to build</h2>

<p>The most important thing I can tell you is that you must be really, <em>really</em> ruthless in throwing out ideas, or at least pushing to post launch. There's so many more features, countless enhancements that I really want to add, and wanted to add before I launched. You have to ask yourself if it really matters. Really? Are you sure? I threw out a tonne of features that I though I needed. Not just big ideas but simple, basic things.</p>

<p>Do you really need to implement pagination in your backend? Not until you have customers with unwieldy lists of stuff, and that's not going to be for a while after launch most likely! Do you need an admin backend for yourself? Not if you're a programmer, just use the database console. If it starts to piss you off you can write something at that point to fix it. All of the assumptions that you have if you've been building software for other people for most of your career are now open to questioning.</p>]]></description><link>http://alexspeller.com/building-a-company-in-42-days-with-40-dollars/</link><guid isPermaLink="false">3d132ae3-ab53-4d4b-88b9-ba11badf4880</guid><dc:creator><![CDATA[Alex Speller]]></dc:creator><pubDate>Tue, 08 May 2012 11:00:00 GMT</pubDate></item></channel></rss>