Simple inheritance with Ember.js

When doing Object-oriented programming, we are always seeking ways to reduce the duplication in the code we write. Reusing existing code is something that every programmer wants to do most of the time. Because, we have to admit it, we are pretty lazy. But that laziness brings us great stuff like frameworks we use in our everyday jobs.

Using Ember.js and ember-cli of course, there is an easy way to remove code duplication. Ember.js has a nice way to extend every existing class, you are already programming apps in Ember that way, by extending Ember.Route, Ember.Component, Ember.Controller and a lot of other stuff in the framework.

Realising this nice thing will help us on our way of achieving maximum code reuse. Let’s say we have an component bird

// app/components/my-bird.js
import Ember from 'ember';

export default Ember.Component.extend({
  name: 'Birdie McBird',
  actions: {
    fly: function() {
      alert("I'm flying, la la");
    },
    speak: function() {
      alert('Tweet');
    }
  }
});

And we want to implement some of the same actions in the duck component, because all ducks can fly, but they just sound different, so we would do it like this:

// app/components/my-duck.js
import MyBirdComponent from 'my-bird';

export default MyBirdComponent.extend({
  name: 'Ducky McQuack',
  actions: {
    speak: function() {
      alert('Quack!');
    },
    waddle: function() {
      alert('Waddle waddle!');
    }
  }
});

Of course, we have to define our templates, and link the actions inside them, so here it goes:

<!-- app/templates/components/my-bird.hbs -->
<h2>Hello, my name is {{name}}!</h2>
<button {{action 'speak'}}>Make a sound</button>
<button {{action 'fly'}}>Fly birdie fly</button>

<!-- app/templates/components/my-duck.hbs -->
<h2>Hello, my name is {{name}}!</h2>
<button {{action 'speak'}}>Make a sound</button>
<button {{action 'fly'}}>Fly birdie fly</button>
<button {{action 'waddle'}}>Make a move, duck</button>

<!-- app/templates/application.hbs -->
{{my-bird}}
<br>
{{my-duck}}

In Ember 2.0 you will be able to reference components with the angle bracket notation, just like any other regular html tag. I’ll write about those new features sometime in the future.

If you run the example, you see that we are reusing the speak method and redefining everything else, which is great. This is a really simplified example, and done with a component. You can do the same thing with controllers, models, even routes.

I’ve made a small demo on JSFiddle so you can try for yourself. Of course, it’s a globals based Ember app, but it’s the same principle as described here. And because ember-cli is the default way of developing Ember.js apps nowadays, I’ll keep my ember posts using it.

Notify an Ember.js app that a deployment has happened

The approach with refreshing regular web applications after deployment is pretty straightforward, you click on a link, it goes to the server, server renders a page. If the deployment has happened in the meantime, server renders you the current(new) version of the page. The issue with Ember.js is a pretty nice example of how the old approach doesn’t work anymore. You get the whole application when you first request the page, then everything happens in the browser. The only thing that goes between server and the client is the JSON being passed here and there.

Luckily we are already using Sam Saffron’s awesome gem message_bus, to notify the front-end that an update has happened in a model we are working on. So I decided to implement deployment notification using a similar approach.

First, we want to be able for the Ember app to know that a deployment has happened, so registering MessageBus and subscribing it to a channel is the first thing we will do. We chose the ApplicationController for this in Ember, because it is always loaded, regardless of the route. We are using ember-cli-growl component to provide us with growl like notifications, so you might need to adapt the code to suit your needs.

/* global MessageBus */
import Ember from 'ember';

export default Ember.Controller.extend({
 initMessageBus: function() {
 MessageBus.start();
 MessageBus.callbackInterval = 50;
 },
 subscribe: function() {
 var channel = '/deployment';
 var controller = this;
 MessageBus.subscribe(channel, function() {
 controller.growl.info('A new application version has been deployed, please reload the browser page.', { clickToDismiss: true });
 });
 },
 init: function() {
 this._super();
 this.initMessageBus();
 this.subscribe();
 }
});

In Rails, include the message_bus gem in the Gemfile, bundle install and run the console. Now you can try running MessageBus.publish('/deployment', 'foo') and you should see a notification pop up in your ember app. Ok, but we need to be able to call it somehow, and what better way to do it than using Rake.

desc "notifies Ember that a deploy has happened"
task notify_ember: :environment
 MessageBus.publish('/deployment', '')
end

Now you only have to call that task on the server when your deployment has finished and everything will be fine and dandy. There are a lot of options to do this, depending of your deployment strategies, and infrastructure. We are using Capistrano, so a nice after hook, running after the app server has restarted did the job quite well. If you are having trouble setting it up, feel free to ping me in the contact form.

Speed up Rails on Heroku by using Rack::Zippy

I really like Heroku for fast deployments and everything they offer for a small Ruby on Rails or node.js apps. It’s so easy to deploy a web app there, and it’s pretty much free unless you are doing some serious stuff, by when you should already be paying either Heroku, or have your own dedicated solution when you’re all grown up.

There is one thing that I personally dislike about Heroku, and that is their asset serving. As we are all sitting behind a desktop(laptop) computer, and have pretty good network connections, we don’t see how slow the app is for someone on 3G mobile network, or something even slower. And in a well written app, the main culprit for large data transfers are the assets.

We have a lot of JavaScript, Css and images in our apps, because we want to make them beautiful, but that takes it’s toll on network bandwidth. Luckily most browsers support compressed assets(js and css) and know how to decompress them. And when you build your own server, there is a very high probability that assets won’t be served through Rails at all. You will either use NGINX or Apache httpd to act as a reverse proxy, and also serve your assets for you. The web server is smart enough to serve compressed assets to browsers that support them, and uncompressed to others.

Rails has a pretty good ActionDispatch::Static rack middleware that does all the work for us while in development, or on heroku by changing a config flag, or using their rails_12factor gem in production. To get it running you have to change the static flag inside the config/environments/production.rb

 # rails 4.1 and below
 config.serve_static_assets = true
 # rails 4.2 and above
 config.serve_static_files = true

For those on a budget, and not able to afford to serve assets from Amazon S3 or another CDN (will update here when my post on how to do that is finished), there is an option on serving the compressed assets from rails. They are already generated by heroku on deploy, but just aren’t being served, which considerably increases your initial page load time, and every additional one, if the assets aren’t being properly cached. ` You can solve this pretty big issue with including one gem that will serve compressed assets for you. It’s called Rack::Zippy and it’s really easy to configure. You have to add it to the Gemfile first:

gem 'rack-zippy'

Run the bundle command and create the initializer for Rack::Zippy in config/initializers/rack_zippy.rb like this:

Rails.application.config.middleware.swap(ActionDispatch::Static, Rack::Zippy::AssetServer)

This will use Rack::Zippy to server gzipped assets instead of uncompressed ones and really reduce your initial load time, especially on slow connections. It also adds pretty sane cache expiration headers which can also help with the browser caching.

A not so funny orphaning issue or Rails’s has_one relationships

If you are using ActiveRecord and keeping your models pretty thin and properly normalized, you will surely reach for the very nice has_one relationship. It’s basically a one to many relationship, but Rails thinks for you and keeps only one child model available for use.

It’s pretty easy to set up, given that you have two models, let’s say Post and Post::Metadata

class Post < ActiveRecord::Base
  has_one :post_metadata
end

class Post::Metadata
  belongs_to :post
end

OK, this part is pretty straightforward, you create your records either by using Post::Metadata.create(post_id: 42, other_attrs) or by using Post.find(42).create_post_metadata(attrs). If there already is a has_one child record, and you create a new one, the old one will be orphaned, which is a default option, and you should be thinking of it before you start messing around. This can also be the desired option, maybe you are storing some photo url’s that aren’t being used anymore, and have a callback on them to destroy the record after you remove the file from the third party storage.

There is one tiny kink that cost me a few hours of life today, although you create a child record in a has_one relationship, the mere action of building an association (just instantiating it, not creating) is enough to orphan the previous record, without it rolling back if the newly built record is destroyed.

Automated testing will add value to your software project

We have read enough about TDD and it’s demise in the last year. Since David published his post about how TDD is dead there have been a couple of flame wars concerning TDD and testing in general.

I believe that TDD is a good thing, but I don’t always practice it, as sometimes you don’t have the time to do it. I know, some of you reading this will say that there you must make time for TDD and that TDD is the only way. Maybe you are correct, but in a startup world there is rarely any time for testing at all.

With deadlines and churning new features each week, one can’t make the time to do proper TDD. And sometimes it seems that TDD is some relic from the past, from the really distant past. There is a nice report called Why Most Unit Testing is Waste that sums it up fairly good.

However, I believe in automated testing, at least having a full integration suite, following the application happy path, and any edge case you find later on. Also I’m not against unit testing, if it makes sense. Payment processing code, of course you will test it. Some code deciding if the label class is blue or red, well, you can probably skip that test if you have no time to write it. Rails controller tests are a great example of procrastination in tests. I don’t have anything smart to work on, let’s write a couple useless controller tests.

Unit testing external libraries is another thing, they should be properly tested, to ensure that their API behaves as it claims. Especially if your library is public, then you have to test it.

Having a thorough test suite increases the application value, and decreases the breakability because any subsequent change you make on an application that isn’t tested is like walking through a minefield. You never know what will break.

I would have liked that I learned this lesson the easy way, by listening to other people having issues when some of their code wasn’t tested and they had to change just one little thing, and something completely unrelated broke. However, that wasn’t the case, I learned it the hard way. With a really bad client, who constantly changed their mind about features (another red flag) we were implementing a lot of stuff, and changing it on a daily basis. Having no tests meant that you expected something else will break after deploy, because you just don’t know what can go wrong.

After I got burned by that, I started writing tests, trying to do TDD, but at least covering the process with integration tests as I went along. And it helped a lot, the sheer confidence when deploying the app that nothing will go wrong is really enough. And the client is better off in the long run, because there is no chance that the code breaks, and no one notices it.

Lesson learned: Don’t obsess with TDD or the proper way to test, but try to test the code as well as you can, have an integration/acceptance suite that you run before deploying, and try to cover as much of the app as possible with it. Don’t overdo it, and don’t test the language or framework you are using. Shaving Yaks is really fun sometimes, but don’t do it on a production application, because someone will read it later on, and think that you have to test every little thing.