Category Archives: Software Engineering

Ember JS Flash Message Alerts

There are lots of ways to do this and some plugins out there (eg aexmachina’s ember-notify and poteto’s ember-cli-flash) but here is my take* on Rails style flash messages for Ember as seen in the Open PHACTS Explorer 2.

Use a simple array controller to keep track of the current messages, a model to hold the message and what type of alert it is, a view with an action to remove the alert and a template to show it on the page.

The page needs a template containing the flash messages.

<script type="text/x-handlebars">
    {{#each flashMessage in controllers.flash.content}}
        {{view "flash" contentBinding="flashMessage"}}
    {{/each}}
</script>

It also needs a template for the flash message.

<script type='text/x-handlebars' id='flash'>
    {{#if flashMessage.isNotice}}
    <div class="alert notice">
        {{flashMessage.message}}
        <button type="button" class="right" {{action "click" flashMessage target=view}}><span>×</span></button>
    </div>
    {{/if}}
    {{#if flashMessage.isSuccess}}
    <div class="alert success">
        <button type="button" class="right" {{action "click" flashMessage target=view}}><span>×</span></button>
        {{flashMessage.message}}
    </div>
    {{/if}}
    {{#if flashMessage.isError}}
    <div class="alert error">
        <button type="button" class="right" {{action "click" flashMessage target=view}}><span>×</span></button>
        {{flashMessage.message}}
    </div>
    {{/if}}
</script>

We need a controller to keep track of all the flash messages

App.FlashController = Ember.ArrayController.extend({
    createFlash: function(options) {
        if (options.type !== null && options.message !== null) {
            this.pushObject(this.get('store').createRecord(
                "flashMessage", {
                    type: options.type,
                    message: options.message
                }
            ));
        }
    }
});

We also need model for a flash message.

App.FlashMessage = DS.Model.extend({
    type: DS.attr('string'),
    message: DS.attr('string'),
    isNotice: function() {
        return this.get("type") === "notice";
    }.property("type"),
    isSuccess: function() {
        return this.get("type") === "success";
    }.property("type"),
    isError: function() {
        return this.get("type") === "error";
    }.property("type")
});

If a controller wants to create a flash message then it ‘needs’ the Flash controller. Here the Application controller creates a flash message in response to an action.

App.ApplicationController = Ember.Controller.extend({
    needs: ['flash'],
    actions: {
        createFlashNotice: function() {
            this.get('controllers.flash').createFlash({
                type: "notice",
                message: "I'm a flash notice."
            });
        },
        createFlashError: function() {
            this.get('controllers.flash').createFlash({
                type: "error",
                message: "I'm a flash error."
            });
        },
        createFlashSuccess: function() {
            this.get('controllers.flash').createFlash({
                type: "success",
                message: "I'm a flash success."
            });
        }
    }
});

We need a view for a flash messages which can remove it in response to a user action.

App.FlashView = Ember.View.extend({
    templateName: 'flash',
    classNames: ['hide'],
    didInsertElement: function() {
        this.$().fadeIn(1000);
    },
    actions: {
        click: function(alert) {
            this.get('controller').get(
                'controllers.flash').removeObject(
                this.get('content'));
            this.destroy();
        }
    }
});

JS Bin example. Click on one of the buttons to create a flash message and remove it by clicking on the ‘x’.

Thanks to Eric Berry for the ‘flash’ of inspiration.

* I originally wrote this for the Ember guides cookbook but they are moving away from this format and relying on blog posts etc instead.

Ember 1.10

(It’s been a while….)
So, a few months after updating to Ember 1.7 in the Open PHACTS Explorer 2 I had a look at what the Ember folks have been up to. The latest release is now 1.10 with 1.11 just around the corner. Wow. It’s not a straightforward update to 1.10 but not too hard either. Here are the headlines.

each helper

The {{#each}} helper now requires the scope instead of inferring it from the controller. So you need to change

{{#each}}
{{this.title}}
{{/each}}

to

{{#each post in model}}
{{post.title}}
{{/each}}

view helper

Syntax like {{View Ember.TextArea}} is now {{textarea}}. You will see an error mentioning the global lookup of views….

Template compiler

With the transition towards the HTMLBars templating engine you will need to include the ember template compiler in your code. You can get it from http://builds.emberjs.com/release/ember-template-compiler.js.

I have changed my old blog example to meet these new requirements.

Ember is also embracing NodeJS with how Ember apps are created and structured and it is worth looking at Ember CLI to get yourself prepared. It is mentioned on the Ember homepage but the documentation has not yet found its way into the main Ember guides.

You want to do what? There’s an app for that…….

tl;dr I don’t want to write web applications which have code to do everything the world could conceivably want to use it for. I want the web to tell me what other applications can do that thing. The Web Intents standard met that requirement before it was abandoned.

The problem

The Open PHACTS Explorer is a Javascript based web application which is used to browse the Open PHACTS Pharmacology API. As well as showing facts about compounds, proteins, pathways etc. it can also be used to view and edit compound structures. It use ketcher for this. In an iFrame. Ouch. Writing our own version of this would take a long time and isn’t really our core business. Another part of the application shows proteins and a branch can render these in 3D using GLmol. This required some integration which took time we rarely have and there is always the worry that introducing a 3rd party piece of code could break your application in ways you do not notice.
What I really want is for 3rd party ‘widgets’ to take over the heavy loading for those bits of the application. If you click on a link to a PDF or on a mailto: link the browser knows what to do with those things. How cool would it be if the same could be done for a link to a molecule in PDB or a compound SMILES property. The browser would know that the link was to a SMILES through some magic formatting and pop up a dialog box – “Do you want to go to the page for that compound or view it in the compound editor?”.

The solution

The Android mobile platform has the concept of “Intents“. When you click on an email link it asks you what application you want to use to fulfil this “Intent”. When you design an application for Android you tell the outside world what Intents your application can handle. This lets the device give you the option of using it when you want to do something that application can handle.
Imagine if you could do the same in a desktop web application.
Enter the “Web intent“. This a W3C specification which defines a method for client side (i.e. browser) service discovery. An application registers it’s intents via an html tag like below or in a web application manifest file.


<intent action="http://webintents.org/share"
type="image/*"
href="share.html"
disposition="window|inline"></intent>

A client application uses an intent using some javascript


var intent = new Intent("http://webintents.org/share",
"text/uri-list",
"http://news.bbc.co.uk");
window.navigator.startActivity(intent);

The browser then tries to find any installed apps which meet the intent. In this case a URL sharing application. Sounds perfect. But it was not to be.

Warning: Deprecated in Chrome 24. Web intents are no longer supported.

See here for details.

The future

Maybe there is some light at the end of the web intents tunnel though. This post implies that Mozilla might be actively looking at something and google may be willing to join them. Other people are thinking about specifications.

Putting all the pieces together

In parallel to the Open PHACTS Explorer we have been providing widgets to the BioJS registry. A BioJS widget is a snippet of HTML, CSS & JS with a documented API which generally does one life science type of thing. For example here is a compound info page. Click on the Edit button to see the re-usable code in JSBin. The registry is a little bit rough round the edges at the moment but the idea seems pretty sound. Imagine if you could easily install one of these widgets in your browser just by clicking a button which also meant that the widget registered its intents. Any web page you were viewing could then use that widgets intents.
Imagine then if you then clicked on a link on that page and your browser couldn’t handle that intent but knows that there are some apps in the chrome/firefox/whatever store that could. It could then take you to a page allowing you to decide which of these you wanted to use. Maybe the intent information is actually embedded in the links href or other property and doesn’t even need any Javascript like the Web Intents spec implied.
It is quite possible in the future that the BioJS widgets could also be packaged up as web components. This would seem to be a perfect match for Web Intents. Or this another dead end?

Who has the influence?

As a final point I make the following observation.

There always seems to be several different complimentary (or conflicting depending on your point of view) things happening in the web standards world at any one time. How does anyone manage to keep track of them? How do they then manage to influence them while keeping their workload to a sensible level and sanity intact? Answers on a postcard……

IE6 is dead, maybe we can move on

Now that IE6, 7 & 8 have been sent to the heavenly software repository(1) it’s maybe time to stop relying on jQuery quite so much and have a look at some of the ‘new’ things which javascript ES5 can do natively. We’ve been clinging on to things like $.each and $.isArray when javascript and most browsers can do it natively using Array.forEach and Array.isArray.
If you really, really, really have to support these old browsers then maybe you can just use the polyfills in the mozilla reference, at least then you can definitely move on and use Javascript as it should be.
As the ES5 reference shows there is widespread support for most of the features, unfortunately the same cannot be said for ES6 yet.

(1) Rumours of their complete death may be exaggerated but the downward trend gives us hope for the future.

Coding without coding: announcing the Open PHACTS HTML widgets

What if you could have an element in your web page which is replaced by some HTML depicting some really cool chemistry stuff without having to know a lot about HTML, CSS, Javascript or how the Open PHACTS API works. Well, that’s our intention with the OPS HTML widgets. It’s built using the ideas and templates we designed for the Explorer but without the full Ember JS MVC stack. It’s early days for the library and there are only a couple of widgets available right now. We are also looking at aligning with BioJS.

Just by adding a div with a specific class and a data attribute you can get facts (phacts!) and images for chemical compounds and targets embedded in your page with no need to know anything about the Open PHACTS API.
You need to load the jquery, handlebars, ops.js and ops-html-widgets libraries in your page and then you can either insert the info using a div like


<div id="compound-info-div" style="display: none;"/>

or programatically using some javascript like


var compoundWidget = new Openphacts.CompoundWidget(appUrl, appID, appKey); compoundWidget.infoByURI("http://www.conceptwiki.org/concept/dd758846-1dac-4f0d-a329-06af9a7fa413", "compound-info-div");

You can style the divs and include as much or as little info you want using simple handlebars tags like


<div id="compound-info-div" style="display: none;">
  <div>Preferred Label: {{prefLabel}}</div>
  <div>SMILES: {{smiles}}</div>
  <div>Inchi: {{inchi}}</div>
</div>

The results from one of these compound-info-divs has magically appeared below. Honest.




Ruby 1.9.3 on Scientific Linux (& Centos)

The default Ruby on Red Hat (Enterprise) based distros is still 1.8.7 which is almost completely unsupported. I don’t like using RVM on production machines since I don’t want to manually update versions. A search around the web revealed that RHEL provide extra packages as software collections. Scientific Linux also has this collection available here.
I installed this on a fresh machine with no Ruby installed, it might be a good idea to remove any 1.8.7 packages first with

yum remove ruby

I though you could just run

yum install yum-conf-softwarecollections

but I couldn’t get it to work so just downloaded the rpm and installed from the local file with

rpm -ivh yum-conf-softwarecollections-1.0-1.el6.noarch.rpm

Then you can install ruby 1.9.3 with

yum install ruby193

However, Ruby probably won’t be on your path yet. It is installed in /opt/rh/ruby193/. Inside this directory is a file called enable which has the commands to add the binaries etc to your path and also the shared libraries. Add these commands to your .bashrc, update your environment with

. .bashrc

and run

ruby -v

We also need to ensure that apache can pick it up, I have added it to the top of /etc/init.d/httpd, hopefully that will be enough. Another issue is delayed job, we need to ensure that the delayed job daemon is using the version of ruby we installed. Perhaps adding it to the delayed job startup script will do the trick.

Here is some info about software collections for Centos which I have not had a chance to try but looks like a good bet.

Good luck.

Delayed Job missing method in production fixed

A few months ago I had an issue
with phusion passenger not starting due to a missing delayed job method. Yesterday I finally got round to figuring out why. Turns out that the delayed job gem was being loaded in the rails assets group in the Gemfile which of course are not used in production. Usually it only takes an hour or 2 away from the keyboard to spot these things. This time it seems there were a lot of trees obscuring the wood.

Helping contributors to help you with 5 simple rules

Helping out in open source projects is easier than ever using systems like git and github. However, you need to ensure that any code sent to you is as easy as possible to merge. On our OPS.js project we added these 5 simple rules to make everyone’s life easier.

1. Fork the project.
2. Checkout develop branch.
3. Create a new branch based on develop and change the code.
4. Write some tests.
5. Submit patch.

Ember 1.0 – rise from the ashes

We have been moving our explorer2 app to use the released version of Ember (1.0) and the accompanying Ember Data (1.0.0 beta 3). There have been lots of changes to Ember Data which you can find here.

Ember changes
Ember itself has not changed too much between RC and release but here are some things we noticed

1) Refer to routes inside quotes in linkTo blocks

Previously we had

{{#linkTo post.comment comment}}{{comment.text}}{{/linkTo}} 

which is now

{{#linkTo 'post.comment' comment}}{{comment.text}}{{/linkTo}}

2) Define hasMany etc relationships as ‘async’ in models
If the child models are loaded as something like “comment_ids”:[1,2] in the server json response then

comments: DS.hasMany('comment')

should now be

comments: DS.hasMany('comment', { async: true })

3) hasMany etc relationships are now simple strings rather than referring to the model type

 DS.hasMany('App.Comment')

is now

 DS.hasMany('comment')

4) controller actions now inside ‘actions hash’.
Inside your controller put your actions inside a block like this:

actions: {
  someAction: function(){},
  anotherAction: function(){}
}

Ember Data Changes
There are some really important Ember Data changes, here are some highlights

1) Per model adapters.

Each model can have its own adapter to find data etc. This is really useful if you create your model from ‘non-standard’ json or assign your own ids.
Here is an example from explorer2 where we grab some json from a server and create the model on the fly.

App.CompoundAdapter = DS.Adapter.extend({
  find: function(store, type, id) {
    // return a promise inside of which is the callback which either resolves with the retrieved compound data or rejects with the status
    var promise = new Ember.RSVP.Promise(function(resolve, reject){
      var searcher = new Openphacts.CompoundSearch(ldaBaseUrl, appID, appKey);
      var pathwaysSearcher = new Openphacts.PathwaySearch(ldaBaseUrl, appID, appKey);
      // get the compound details  
	  var callback=function(success, status, response){  
        if (success) {
	    var compoundResult = searcher.parseCompoundResponse(response);
            compoundResult['pathways'] = [];
            resolve(compoundResult);
        } else {
            reject(status);
        }
      }
      searcher.fetchCompound('http://www.conceptwiki.org/concept/' + id, null, callback);
    });
    return promise;
  }
});

2) Promises and chaining.

Ember data makes heavy use of Promises (https://github.com/tildeio/rsvp.js). When finding models you resolve or reject from within the promise and can even chain them together if you need to do something else once you have found/created a model. The adapter example above demonstrates a simple promise. Here is an example of a promise chain where we find a model and then do something with it after it is found.

me.get('store').find('compound', url.split('/').pop()).then(function(compound) {
  thisCompound.get('structure').pushObject(compound);
});

3) Find uses the store, not the model
Before we would have

App.Post.find(1)

now we have

store.find('post', 1)

Similarly when creating we do

store.createRecord('post', {title: 'a great post'})

4) onCreate, transactions gone – use promises
previously we would listen to the ‘onCreate’ action of a model and then do something with it. Now do

post.save().then(function(post){
  //do something
});

5) Underscored keys needs different serializer

If your relationships are sent as underscored values in the json, for example:

{"comment":{"id":4,"text":"comment 3","post_id":1}}

Then you need to tell Ember Data by creating an ApplicationSerializer with

App.ApplicationSerializer = DS.ActiveModelSerializer.extend({});

Otherwise your json will look like

{"comment":{"id":4,"text":"comment 3",post:1}}

which in our case breaks the default rails behaviour.

6) Add child model to parent after save
Inside the promise when saving a child model you need to add it to the parent or it will not be shown when transitioning. In this example we save a comment for a post, add it to the posts array of comments and then transition to the index for that post. You could also reload the parent model instead, not sure what the preferred/correct behaviour should be.

comment.save().then(function(comment){
        //post.reload(); //could do this instead
        post.get('comments').pushObject(comment);
        me.get('target').transitionTo('post');
      });

Overall, quite a lot of changes but I think they make Ember easier to use and hopefully make it stable (for a little while at least). You can find an updated simple blog app with the latest changes here. The non rails version using fixture adapter is here with jsfiddle here.