July 11, 2014
Run A Javascript Console Inside Sublime Text

It’s very simple. We’ll use Node.js to compile and run javascript. This comes with Google’s V8 JS engine and its own set of rich libraries/ modules. Here goes:

  1. Install Node.js using the conventional ‘.configure’, ‘make’, ‘make install’ trio. Put it in common location or add the installed dir to $PATH.

  2. In sublime text, create a new build system: ‘Tools > Build System > New Build System…’. This creates a new file with build template.

  3. Modify the file as below:

    "cmd": ["node", "$file"]
  4. Save it as


  5. A new entry “JavaScript” (i.e. name given to the new build file) should come in Tools > Build System menu. Done. Just to test, create a ‘test.js’ with

    console.log("Hello, World!);

    in it. Build and run the file using Command+B or menu item as you like.

    'nuff said.

June 28, 2014
Rspec is better for humans

Below is a reprint of a post regarding Rspec’s new syntax change originally posted on May of 2013 by one it’s developers samphippen (listed as fourth developer at the time of my posting this article).

I’m reprinting this here as I’ve found his article to be useful in helping me write a few of my test in the new syntax

If your are a student of Test Driven Development, this will be important to you. I like the new syntax personally. It makes Rspec even more “human” readable. As an earlier student myself, I found the whole field of testing to be interesting, frustrating and confusing. Earlier it was very hard to find resources that explained how to use and write rspec that didn’t talk like advanced level software engineers. Which of course makes adoption of a tool even slower going since you first have to “learn latin” in order to understand what the doctors are talking about. A very foolish human phenomenon but I’m rambling here’s Sam’s post

[note: this post is regarding rspec release candidate 2.14. Rspec is currently at version 3 at the time of this post]

RSpec’s new message expectation syntax

27 May 2013

We’ve developed a new syntax for message expectations in RSpec, which brings message expectations in line with the new expect syntax for state based expectations. This change required us to make a number of internal refactorings, so we’re cutting a release candidate of RSpec, 2.14rc1, so that early adopters can try this new feature out. We encourage you to try out the release candidate and report any issues to https://github.com/rspec/rspec-mocks/issues.

In 2.14rc1 both the new syntax and old syntax are enabled by default. This is in line with state based expectations, where both syntaxes are also enabled by default.

With the old syntax message expectations were set like this:


The new syntax for message expectations looks like this:

expect(foo).to receive(:bar)
expect(foo).to receive(:bar).with(:buzz)
expect(foo).to receive(:bar).exactly(3).times

This syntax also adds new ways to stub methods. Previously you may have stubbed like this:

d = double(:message1 => true)

You can now stub like this:

d = double(:message1 => true)
allow(d).to receive(:message2).and_return(:value)
allow(real_object).to receive(:message).and_return(:value)

If you want to configure which syntaxes are enabled you can do so as follows (see your spec_helper.rb file):

RSpec.configure do |configuration|
  configuration.mock_with :rspec do |configuration|
    configuration.syntax = [:expect, :should]
    #configuration.syntax = :should
    #configuration.syntax = :expect

Myron’s post explains why using the expect syntax is preferable to the should syntax in some cases. The problem here is that the :should syntax that RSpec uses can fail in the case of proxy objects, and objects that include the delegate module. Essentially it requires that we define methods on every object in the system. Not owning every object means that we cannot ensure this works in a consistent manner. The expect syntax gets around this problem by not relying on RSpec specific methods being defined on every object in the system.

We think that the new :expect syntax for message expectations is an improvement, and that you should try it in your fresh and existing spec suites. You can get the new syntax by upgrading to RSpec 2.14rc1, and we encourage you to do so.

Ok so that’s it for Sam’s original post. As I mentioned above, Rspec is currently at version 3.0.0. You can follow the teams progress by following them on twitter and keeping tabs on Myron’s (the lead developer) blog.



and keep up with me


June 27, 2014
API tutorial - build an api consumer app

Note: I’ve created a sample API_provider application in this post. We will use that app later in this tutorial

In this tutorial I’ll show you how to create an API_consumer app to register, update or delete a user on the API_provider app database.

You can see that the API_provider has documented the url, authentication, expected data type and data required to fulfil your request. As long as you can provide those criteria, you can write your API_consumer code in any language. Here I will stick to Ruby.

Ruby has an inbuilt library to manage making API calls, retrieving the returned response, and parsing it to reuse it in your own application. Here are links to those libraries.



You could use the above two libraries to write your API_consumer class. However the ruby community has a number of Gems available to help you with this already, some of them are : rest-client , faraday and httparty. For this lesson we will use the rest-client gem.

Now Let us make an application which will consume the API that I’ve developed in my other post(SEE LINK AT TOP OF PAGE). The API provides functionality to manage a user, so in our application we will not store a user in our own database, but will register it, update and delete it with the API_consumer app.

I am assuming that you have implemented a users controller at some point of time, where you have implemented index , new, create, edit, update and destroy method. Here the view, routes and everything remain the same, only the Users controller code will change, as now, it will interact, not with your local Database, but with the API_provider app Database.

Let us create our Rails Application, which will consume the user management API

STEP 1: generate the rails app

$ rails new api_consumer

STEP 2: add rest-client gems to your Gemfile

gem ‘rest-client’

run bundle install on the terminal

$ bundle install

STEP 3: generate the user controller

$ rails g controller users

STEP 4: add the routes for users resource in your routes

ApiConsumer::Application.routes.draw do
    resources :users

STEP 5: Write the users controller code.

Users controller will have the same actions and flow as you have seen in your users controller, except that, here you interact with the API provider database through its API call. IF you see the API provider document, you can see that it has provided you the authentication login, the url, and the expected data format.

You just have to make a call to this URL and handle the returned data in your application. Now-a-days API return data is in json format in general, but in case they return data in some other format say SOAP, then you have to adjust your code accordingly. The API provider whose service we are going to use returns JSON data by default i.e. if you do not provide a format in the URL, it will return JSON data.

So below is our users_controller.rb code:

NOTE : See the use of get post put and delete call of the REST client. It will decide which action of the API provider will be called for a certain URL

class UsersController < ApplicationController
  require 'rest_client'

  USERNAME = "thefonso" # needed to access the APi
  PASSWORD = "rebelbase" # needed to access the APi
  API_BASE_URL = "http://localhost:3000/api" # base url of the API

  def index
    # specifying json format in the URl
    uri = "#{API_BASE_URL}/users.json"
    # It will create new rest-client resource so that we can call different methods of it
    rest_resource = RestClient::Resource.new(uri, USERNAME, PASSWORD)

    # this next line will give you back all the details in json format, 
    #but it will be wrapped as a string, so we will parse it in the next step.
    users = rest_resource.get 

    # we will convert the return data into an array of hash. see json data parsing here
    @users = JSON.parse(users, :symbolize_names => true)

  def new


  def create
    uri = "#{API_BASE_URL}/users"
    payload = params.to_json # converting the params to json
    rest_resource = RestClient::Resource.new(uri, USERNAME, PASSWORD)
      rest_resource.post payload , :content_type => "application/json"
      flash[:notice] = "User Saved successfully"
      redirect_to users_path # redirect back to index page, which now list the newly created user
    rescue Exception => e
     flash[:error] = "User Failed to save"
     render :new

  def edit
    uri = "#{API_BASE_URL}/users/#{params[:id]}.json" # specifying format as json so that 
                                                      #json data is returned 
    rest_resource = RestClient::Resource.new(uri, USERNAME, PASSWORD)
    users = rest_resource.get
    @user = JSON.parse(users, :symbolize_names => true)

  def update
    uri = "#{API_BASE_URL}/users/#{params[:id]}"
    payload = params.to_json
    rest_resource = RestClient::Resource.new(uri, USERNAME, PASSWORD)
      rest_resource.put payload , :content_type => "application/json"
      flash[:notice] = "User Updated successfully"
    rescue Exception => e
      flash[:error] = "User Failed to Update"
    redirect_to users_path

  def destroy
    uri = "#{API_BASE_URL}/users/#{params[:id]}"
    rest_resource = RestClient::Resource.new(uri, USERNAME, PASSWORD)
     flash[:notice] = "User Deleted successfully"
    rescue Exception => e
     flash[:error] = "User Failed to Delete"
    redirect_to users_path

STEP 6 : Create the corresponding views for the controller action


It will list all the user detail returned by the API, it will provide a “create new user” link to create a new user, also each record will have an Edit | Delete link. Clicking the edit link will take the user to the edit page where they will modify their detail and the Delete action will delete the user.

<%= link_to "Create New User", new_user_path %>
<%if @users.present? %>
  <p>Below is the list of users</p>
  <table width="100%">
    <!-- NOTE : the @users object in our index action is an array of hash, which is generated 
    when we passed return data to the JSON.parse method. If you handled data in some other
    way, modify the code below accordingly. Say for xml data you have to use something like
    u.xpath("id").text instead of u[:id] -->
    <%@users.each do |u|%>
        <%= link_to "Edit", edit_user_path(u[:id]) %> | 
        <%= link_to "Delete", user_path(u[:id]), :method => :delete %>
  <p>No User is Found</p>


Here, as usual, a user will fill up her details and on pressing submit the form will call the create action (via post) of the API and create the new user.

<%= form_tag users_path, :method => :post do %>
   email : <%=text_field_tag :email%><br />
   first_name :<%=text_field_tag :first_name%><br />
   last_name :<%=text_field_tag :last_name%><br/><br/>
   <%=submit_tag "save"%>


User will modify, there details and submit to the update action, which in turn updates the record on the API_provider app database.

<%= form_tag user_path, :method => :put do %>
   email : <%=text_field_tag :email, @user[:email]%><br />
   first_name :<%=text_field_tag :first_name, @user[:first_name]%><br />
   last_name :<%=text_field_tag :last_name, @user[:last_name]%><br/><br/>
   <%=submit_tag "update"%>

STEP 7 : see it working

Now for the fun part. To see this in action you will need to start both the API_provider and API_consumer applications on your local machine…

Start the API provider application on 3000 (the default port).

$ cd to_api_provider_folder

$ rails s # will start the API provider service at port 3000

NOTE: For API consumer code to work, The API provider application must be up and running

Start the API consumer application on some other port, say 3030

$ cd api_consumer

$ rails s -p 3030

Go to the index page of the application:

http://localhost:3030/users # this will show you all users with an edit | delete link and also a create new user link. I hope this useful!

View tutorial readme pages / code:

part 1 - Build an API provider part 2 - a REST client for Firefox here part 3 - How to build a REST client

June 27, 2014
API tutorial - part 1 - build an api provider app

What is an API?

Put in simple words an “API is a program which lets the user use methods of your application from outside of the application”. I will create a REST API here which will implement a CRUD ( create, read, update, delete ) operation on the users table from outside of the application. I assume you all have implemented CRUD for the user in an application before. The API implementation will remain the same, with a few differences listed below.

=> In a normal case, you have a form new.html.erb and edit.html.erb, which provides UI to the user to register themselves and edit their profile respectively. But for an API you do not need any view, as a user does not interact with your application directly, instead, you specify the data that the third party should send to you.

=> There will be no new and edit action in controller, as we do not need any view here

=> We will not do any redirect in our controller action, but just return some data with a status code of success or failure. We may return data in json or xml. As per convention, you should return data as requested by the client calling your API services, so for json request return json data and for xml return xml data.

=> An API does not have any user interface like navigation links or forms to fill out by the user etc. For an API you need to document how it works so that a third party can use it easily. I will write the documentation for the API we create here in STEP 4

STEP 1: writing the routes

namespace :api do
    resources :users, :defaults => { :format => 'json' }

I have put the routes, within api namespace, in this way, it will not conflict with users controller of your actual application, if you have one. If you do not have any, you can simply use resources :users, :defaults => { :format => ‘json’ } , but I suggest to always use a namespace and group all the controllers related to your API in the “api” folder inside your app/controllers directory only.

Also, I have set the default :format here as json . If you do not set it, rails will consider it as an html request if the user does not pass any format. Now from the command line type the following

$ rails generate model User first_name:string last_name:string email:string password:string password_confrimation:string temp_password:string

Once done do the normal rake db:create , rake db:migrate and then travel to your model/user.rb file and enter the following…

STEP 2: generating the model

class User < ActiveRecord::Base
  attr_accessible :first_name, :last_name, :email, :password, :password_confirmation, 

  validates :email, :first_name, :last_name, :presence =>true
  validates_uniqueness_of :email

Thus in model we have validated email and other things, the user calling our API must provide these things. Thus while creating a user the caller must pass :email, :first_name and :last_name. we will generate password dynamically and let the user change it later on.

Note: on line one of our users controller we have “class Api::UsersController”. You will need to create an “api” folder inside your app/controllers directory.

STEP 3 : generating the users controller

class Api::UsersController < ApplicationController
  http_basic_authenticate_with :name => "thefonso", :password => "rebelbase"

  skip_before_filter :authenticate_user! # we do not need authentication here
  before_filter :fetch_user, :except => [:index, :create]

  def fetch_user
     @user = User.find_by_id(params[:id])

  def index
    @users = User.all
    respond_to do |format|
      format.json { render json: @users }
      format.xml { render xml: @users }

  def show
    respond_to do |format|
      format.json { render json: @user }
      format.xml { render xml: @user }

  def create
    @user = User.new(params[:user])
    @user.temp_password = ('a'..'z').to_a.shuffle[0,8].join
    respond_to do |format|
      if @user.save
        format.json { render json: @user, status: :created }
        format.xml { render xml: @user, status: :created }
        format.json { render json: @user.errors, status: :unprocessable_entity }
        format.xml { render xml: @user.errors, status: :unprocessable_entity }

  def update
    respond_to do |format|
      if @user.update_attributes(params[:user])
        format.json { head :no_content, status: :ok }
        format.xml { head :no_content, status: :ok }
        format.json { render json: @user.errors, status: :unprocessable_entity }
        format.xml { render xml: @user.errors, status: :unprocessable_entity }

  def destroy
    respond_to do |format|
      if @user.destroy
        format.json { head :no_content, status: :ok }
        format.xml { head :no_content, status: :ok }
        format.json { render json: @user.errors, status: :unprocessable_entity }
        format.xml { render xml: @user.errors, status: :unprocessable_entity }

STEP 4 : creating API Documentation

With step 3, your API is ready. But how will others use it? You need to tell them how so let’s document the API.


Basic Authentication:

username: thefonso
password: rebelbase

Content Type :

application/xml or application/json


You can pass xml or json data in Body

sample json body

 "email" : "test@yopmail.com", 
 "first_name" : "alfonso", 
 "last_name" : "rush"

Sample xml body


NOTE : Content Type should be set to application/xml for xml data in body and to application/json for json data in body

API Requests:

=> listing users
    url: http://localhost:3000/api/users
    method: GET
    body : not needed

=> Retrieving User detail
    url: http://localhost:3000/api/users/:id 
    method: GET
    body : not needed

=> creating users
    url: http://localhost:3000/api/users
    method: Post
    Body : It can be xml or json

=> Updating User
    url: http://localhost:3000/api/users/:id 
    method: PUT
    Body : It can be xml or json
=> Deleting User 
    url: http://localhost:3000/api/users/:id 
    method: DELETE
    body : not needed

STEP 5: testing the API

You need to write a REST client to use any API. I will explain how to do so in the next post.

You may also try it out by installing a REST client in your browser. I have explained installing a REST client for Firefox here.

You will find method, url, body, header, authentication etc fields there, fill in the details from the documentation in step 4 above. On submitting the details, you will get back a response. Hope it works for you and you receive enlightenment on the basics of understanding API creation :)

View tutorial readme pages / code:

part 1 - Build an API provider

part 2 - a REST client for Firefox here

part 3 - How to build a REST client

January 27, 2014
SublimeText configuration - basic

One of Sublime Text’s many great features is the multitude of plugins/packages readily available, along with the community of devs that create and support them.

This is a list of some of the plugins I use as a web developer, that I think really help my productivity and help me code faster.

1. Package Control

Before you install any plugins in sublime, Package Control is an absolute must that allows you to manage all your packages/plugins through a few keystrokes.

Once installed, press Ctrl+Shift+P or Cmd+Shift+P (mac) and ‘Install package’ to bring up all packages available in the repository.

Get package control

2. Emmet (formerly Zen Coding)

Emmet is a dream to work with for any web developer looking to greatly reduce their keystrokes in both HTML and CSS. HTML abbreviations along with fuzzy logic for CSS are very powerful features that, with a bit of practice, can greatly improve coding efficiency. Let’s say you wanted to create the following structure in HTML:

You might be used to typing ‘div’ or ‘ul’ followed by tab for example to create those nodes. This does make coding quicker but still involves a fair amount of typing. To create the same structure with Emmet, all you need to do is enter the below followed by tab.

That’s only 21 characters compared to 161, a huge time saver! Not only that, Emmet will allow you to tab between key points – in this case the a href and a values.

It’s quite easy to see what’s going on with this example. The hash ‘#’ and dot ‘.’ symbols create the ids and classes, the greater than ‘>’ symbol will create following HTML elements as a child and asterisk ‘*’ repeats elements. Other useful operators include plus ‘+’ to append another element at same level and brackets ‘()’ to group elements.

Here’s an example of CSS with Emmet. Consider:

This can be created by inputting:

Again, 36 characters compared to 162. All you need to do is type a few characters of the style you want, followed by a value (if relevant) and Emmet will try and work out what styles you’re trying to create with fuzzy logic. It will also set multiple cursors and tabbing where relevant.

Get Emmet for Sublime

3. AutoFileName

One of the (very few) things I missed when switching to Sublime from Dreamweaver was the ability to drag and drop assets, files and images from the file panel into code view.

AutoFileName in my opinion is just as good, if not better, than Dreamweaver drag and drop as it removes the need to use the mouse to insert assets. When entering an img src=”“, a href=”” or background-image:url(…); for example, a mini file browser will appear that allows you to (fuzzy) search and select assets.

Inserting images will even display and create the width and height parameters automatically.

Get AutoFileName

4. Sidebar Enchantments

Whilst I’m trying to move to a keyboard only approach, I still find I need to use the sidebar on occasion and sidebar enhancements gives you many additional features that don’t come natively with Sublime such as duplicating files and creating new folders.

These are four great plugins that make sublime easier and more fun to work with.

Liked posts on Tumblr: More liked posts »