Roda + Mutations + Jbuilder = Perfect fit for JSON API

RubyI have been a big Ruby fan for many years and during my Ruby journey I have used various frameworks like Rails, Sinatra and Cuba.

When we started to develop Kontena, a tool to manage and deploy Docker containers, we needed some a simple framework to handle our server-side API. Cuba seemed to fit perfectly to our needs, since it is lightweight and benchmark results have been quite impressive. Then we found Roda framework. Roda is originally a fork from Cuba and seems to solve some Cuba pain points.

The main difference between Roda and Sinatra is that Roda uses a routing tree instead of list of routes. Because of this Roda is 2.5 times faster than Sinatra for small applications.

What is especially nice on Roda, it has a plugin system and all parts of Roda can be overridden by plugins.

How Roda framework is used on Kontena

We are using Roda framework on a Kontena Server component. Kontena Server is a component that controls what is happening on Docker host nodes. We have structured our code quite a conventional way:

app/
….jobs/
….models/
….mutations/
….routes/
….services/
….views/
config/
spec/
config.ru
server.rb

The backbone of application consists of API endpoints that are handled by Roda routes. If you have lots of API endpoints, your route file might grow relatively large. To avoid this issue, we have used Roda’s multi_route plugin to keep route files small and clean:

# /v1/services/:id/containers
r.on ':id/containers' do |id|
  load_grid_service(id)
  r.route 'service_containers'
end
V1::ServicesApi.route('service_containers') do |r|
  # GET /v1/services/:id/containers
  r.get do
    r.is do
      @containers = @grid_service.containers
      render('containers/index')
    end
  end
end

Also in order to keep our route files small and simple, we have used mutations gem to handle business logic of operations. By using mutations gem we achieve thin routes and thin active models and separate business logic into testable units that we can test easily

Since our API returns JSON, we are using Roda’s JSON plugin for simple responses. The JSON plugin allows match blocks to return arrays or hashes, and have those arrays or hashes be converted to JSON, which is used as the response body.

For more complicated responses we are using Jbuilder gem, which works also with Roda framework very well.

base.plugin :render, engine: 'jbuilder', ext: 'json.jbuilder', views: 'app/views/v1'
r.get do
  r.is do
    @grid_service = grid_service
    render('grid_services/show')
  end
  ...
end

So far Roda, Mutations and Jbuilder combination has been worked very well for our needs. We have gain clean code structure, testable code base and good performance for our needs.

Kontena is 100% open source. If you have ideas, bug fixes, improvements,  all contributions are welcome!

Advertisements

Qt Developer Days 2014 Slides: Give a push to your Qt application with WebSockets and Qt Cloud Services

I was at Qt Developer Days 2014 in Berlin and San Francisco this year. I gave there couple of presentations about Qt Cloud Services. The first one was about WebSockets and how you can utilise them very easily with Qt Cloud Services and Qt.

Abstract

WebSockets is an advanced technology that makes it possible to establish an interactive communication session between an online client application and a server. With WebSockets you can send messages to a server and receive event-driven responses without having to poll the server for a reply.

Qt 5.3 introduced new Qt WebSockets module that features full support for WebSocket protocol (RFC-6455). To benefit WebSocket technology with Qt, a server-side implementation is needed to control the message flow. Qt Cloud Services offer two different ways to achieve this goal:
– Managed WebSocket (MWS)
– Managed Application Runtime (MAR)

MWS is a fully managed WebSocket service that will automatically scale with users and supports build-in access control and policies.

MAR is a managed application platform-as-a-service that provides all the tools needed for server-side development.

This presentation covers:
– Overview of WebSockets and common use cases
– Overview of MWS and MAR services
– Basics how to create MWS and MAR instances
– Examples how to benefit MWS in order to send and receive WebSocket messages in a Qt client application
– Examples how to deploy a Qt WebSocket server to MAR and use it in a client application

How to start multiple rails projects just by one command

If you do serious Rails programming, you may have multiple projects for your application. For example you may have one project for an API and another for a web UI. You might also use some background processing like sidekiq etc. Every time you need to launch these services on a development environment, you have to launch all projects in separate consoles manually.

Fortunately there is a better way to do it. By using a gem ‘subcontractor’ together with ‘foreman’ gem, you can define all the projects and services that you want to launch in the ‘Procfile’, for example:

Then you can launch all the projects and services just by one command:

foreman start

How to run Jasmine javascript tests in CI server (Ruby)

Jasmine.js is a great testing framework for Javascript. However running tests in Continuous Integration (CI) server is somehow problematic because the server usually does not have a screen where to open a browser.

The solution is to use Xvfb and headless gem:

Headless is the Ruby interface for Xvfb. It allows you to create a headless display straight from Ruby code, hiding some low-level action. It can also capture images and video from the virtual framebuffer.

To run your tests in CI server, do the following steps:

  1. Install xvfb
    $ sudo apt-get install xvfb
  2. Install firefox
    $ sudo apt-get install firefox
  3. Install headless gem
    $ gem install headless
    or
    add it to Gemfile
    gem ‘headless’
    and run
    $ bundle install
  4. create rake task for headless jasmine runner (https://gist.github.com/nevalla/5591233)
  5. run or add rake task to your build configuration
    rake jasmine:ci:headless

How to implement TreeView with Backbone.js

I started to implement an application that uses backbone.js. One feature that I needed was some kind of treeview as a side menu. I searched some jQuery based treeviews (like jstree and jQuery plugin: Treeview) but they were not suitable as out of the box.

Finally I decided to implement feature by myself. I found that jstree had a very good model of <ul> and <li> element combinations and I went to that direction in my solution as well. See the DEMO

Basically I needed two Backbone View classes: TreeView and TreeViewItem.

TreeView

TreeView class just creates the master <ul>-element (templates/treeview/menu.jst.ejs)

<ul id="menu"></ul>

The class also fetches root level collection of MenuItems and creates TreeViewItem for each item.

TreeViewItem

TreeViewItem has one MenuItem model and a collection of TreeViewItems. In the template (templates/treeview/item.jst.ejs) name of the item is displayed and <ul> element is rendered as sub menu placeholder.

<ins>&nbsp;</ins>
<a href="#"><%= model.escape('name') %></a>
<ul></ul>

TreeViewItem handles clicks from arrow icon (<ins>-element has arrow image as a background) and opens/closes sub menu.

Both views extends Support.CompositeView (from backbone-support library).

Usage

application.js contains required libraries
backbone_treeview.js initializes TreeView class

window.BackboneTreeView = {
    Models: {},
    Collections: {},
    Views: {},

    menu: null,

    initialize: function() {

    },

    initializeMenu: function() {
        this.menu = new BackboneTreeView.Views.TreeView();
        this.menu.render();

    }

};
$(document).ready(function() {

    BackboneTreeView.initializeMenu();
});

How would you improve the implementation and should I make it as a library?

Link to project source: https://github.com/nevalla/backbone-treeview

Mongoid and assets problem on Ruby on Rails 3.2

I was doing my first Ruby on Rails application with MongoDB (via Mongoid gem). When I deployed the application to a production server, assets were compiled correctly but all javascript and css links were still pointing to stylesheets and javascripts folders, like

<link href=”/stylesheets/application.css” media=”screen” rel=”stylesheet” type=”text/css” />

I checked capistrano and server configurations, but nothing were wrong there. Finally I figured out what was causing the problem. I have not required “sprockets/railtie” in the config/application.rb

In the Mongoid documentation especially in ‘Configuration’ section is ‘Getting Rid of Active Record’ subsection which says:

Open myapp/config/application.rb and near the top, remove the line require "rails/all" and add the following lines so you end up with this:

require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "rails/test_unit/railtie"
# require "sprockets/railtie" # Uncomment this line for Rails 3.1+

In a rush I only saw number 3.1 and thought it is okay to leave it as uncommented. Current Rails version is 3.2.8 so should that line be uncommented as default on Mongoid documentation?

My favourite Prototype and Scriptaculous plugins

The unpleasant fact is that Prototype JavaScript framework is dead or at least dying. JQuery is nowadays a de facto JavaScript library and almost all the great tools are designed to use with JQuery (Bootstrap, from Twitter etc).

However there are still lots of people using Prototype or at least would be willing to use it with UI libraries by Scriptaculous and do some awesome stuff. In some level I still prefer Prototype and Scriptaculous to JQuery. Jarvis Badgley has summed this issue very good in his blog post.

If you are stuck with Prototype and Scriptaculous, there are still great and working plugins that extend Prototype and Scriptaculous. I will list now three plugins that I have lately found helpful.

Image gallery & Slideshow

Tom Doyle initially developed Simple image gallery and slideshow and Dave from ISOTOPE Communication has improved the script.

Carousel

Carousel is a highly configurable Prototype extension that creates a nice way of presenting content that is logically broken into several pieces / steps / etc

Accordion

Accordion by Kevin Miller is a lightweight accordion that supports both vertical and horizontal accordions.

Do you use still Prototype and Scriptaculous? Have you any hints or recommendations about great plugins?