Pair program with me! profile for carousel at Stack Overflow, Q&A for professional and enthusiast programmers

8/17/2013

Bootstrap data with Jade templating engine

Jade is templating engine closely related to expressjs. It is not a surprise, since jade is created by a same author. Jade is heavily influenced by syntax of Ruby and Haml.
There are lot of great features in Jade, that makes dealing with compex views on server side really  smooth. One of them is ability to transfer data directly to html ( jade file ), without additional request.
Let me explain that more. We know that HTTP request are expensive. So it is a good pattern to initially load as more content as possible,  so we don't have to make new requests to server. That is  a winning paradigm that  makes single page web applications so powerful on the client side.  On the client, simply load all the view once and make Ajax request for data if needed.  Since Jade is rendered on the server, this approach is especially useful when application needs data from database for the first load.

With Jade we can easily bootstrap data like this:

//
//here data is plain js object
var data = { "name": "myApp","version":0.0.0,"db":"mongodb"};

// now just render existing view, with data object attached   
app.get("/",function(req,res){
    res.render("home",{obj:data}) 
//

In the previous example data object  was local, contained in the same file as main app file. When we want  to bootstrap data from database, we take same approach when rendering jade template.
Again, data is attached to Jade template. The only difference is that we have to have access to database.

Here is example:
//
exports.queryDB = function (req,res) {
    db.collection("jazz",function (err,collection) {
        collection.find().toArray(function (err,collection) {
            res.render("jazz",{giants:collection});
        });
    });
};
//

Database example is a function that asynchronously query data, due to nature af nodejs native mongodb driver. But when we have data, we can manipulate with it with Jade syntax. For example, to iterate over data object and insert it in the html we can do this:

    // 
    ul
        each giant in giants
            li
                a(href="#{giant["name"]}") #{giant["name"]}
    //


Now we have nice list of jazz giants on our page, bootstrapped on first request.

Thanks for visiting my blog.

8/12/2013

Mongodb and underscorejs - the mean stack

I found a way to combine two very powerful toys that I am playing with :

Mongodb - noSQL database that is shaping web these days and Underscorejs  - which make me fell in love with functional programming.

If you don't know already, mongo is using document/oriented key/value way of storing data in JSON format ( BSON - binary JSON under the hood ).
Underscore has a tons of functions that works with literals like plain JS objects and arrays ( which are basic building blocks of mongo collection ). Also, underscore is environment agnostic. That means that it is not dependent on interfaces like DOM. It is important just to execute underscore functions under Javascripot interpreter. Mongo shell is actually javascript shell, so underscore fits great.

To import JS code in mongo, open your .mongorc.js file, that is located in /home/ directory ( Linux/MacOSx), and place any script inside. It can be whole library, like underscore. Now, from terminal, open mongo shell, and type load (".mongorc.js"). Now all code inside that file is avaliable to mongo documents.

Play yourself and have fun.

Thanks for visiting my blog.


8/11/2013

Design patterns refactored

I did some cleaning and refactoring of my implementations of classic design patterns in coffeescript.
Also I included some variations of existing patterns ( adapter, composite ). There is always more than one way in which we can do same thing ( especially with JS ).

Code is  here

Thanks for visiting my blog.

8/09/2013

Local Search Application

I wrote an application that will search through local data store. It can be easily modified to browse remote db also. By default is searches items in a wiki articles, and uses local array-object as storage.
It is written with the help of jQuery and Coffeescript.
I have to mention that it is not structured in object-oriented or modular way. This code is just a basic idea implemented quickly after inspiration. Inside of bigger application of maybe framework it definitly needs structure, optimization, testing and maybe refactoring.

Code can be found here:

Here is a screenshot:



Thanks for visiting my blog.

8/07/2013

Mediator design pattern with coffeescript

This is second pattern in series of Javascript design patterns implemented with coffeescript.
It can be found here:

Coffeeversion:

//
#Behavioral
#Mediator - classical object-oriented design patterns with Coffeescript
#Global objects are here just for testing in the browser
this.mediator = 
    mediate:(x)->
        if x is "from obj1"
            obj2.receive(x)
        else
            obj1.receive(x)
        
this.obj1 = 
    send:(message)->
        mediator.mediate(message)
    receive:(x)->
        console.log " I am obj1, I just received this message from " + x + " with the help of mediator"

this.obj2 = 
    send:(message)->
        mediator.mediate(message)
    receive:(x)->
        console.log " I am obj2, I just received this message from " + x + " with the help of mediator"
//

Compiled to vanillajs:

//
// Generated by CoffeeScript 1.6.2
(function() {
  this.mediator = {
    mediate: function(x) {
      if (x === "from obj1") {
        return obj2.receive(x);
      } else {
        return obj1.receive(x);
      }
    }
  };

  this.obj1 = {
    send: function(message) {
      return mediator.mediate(message);
    },
    receive: function(x) {
      return console.log(" I am obj1, I just received this message from " + x + " with the help of mediator");
    }
  };

  this.obj2 = {
    send: function(message) {
      return mediator.mediate(message);
    },
    receive: function(x) {
      return console.log(" I am obj2, I just received this message from " + x + " with the help of mediator");
    }
  };

}).call(this);

//

Thanks for visiting my blog.

8/05/2013

superTextArea application - HTML textarea on steroids

I wrote small front-end app, that can be found here: https://github.com/carousel/chatBoySlim

Snapshot:



It is HTML textarea, enhanced with some options for styling and a character counter at the bottom. In the future I have a plan to add support for db communication and web-sockets.

Thanks for visiting my blog.


8/02/2013

Classic design patterns in coffeescript

Today I am going to start a series of posts, in which I want to implement classic OO design patterns with the help of coffeescript.  In case you don't know what is coffeescript and what are the benefits of using it, I highly recommend visiting official coffee site: http://coffeescript.org/, and looking for some tutorials online.

So, to start let's define what is design pattern ?

Wiki article says:
In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design
They were introduced to the OO world by the work of GoF ( gang of four ) group, and their famous book:
 http://www.amazon.com/Design-Patterns-Elements-Object-Oriented-ebook/dp/B000SEIBB8

Patterns in this book are discussed from the point of  classic OO languages ( with strong type system, class-based inheritance ...)
Javascript doesn't support these features, but provide some more flexibile and modern paradigms for solving  problems.
It includes prototype based inheritance, no classes, dynamic type system, no block scope, functions as first class. Writing design patterns with Javascript can be challenging. JS is very flexibile, since same things can be done "in more than one way".

First patterns, that I am going to introduce is  Iterator
  
Implementation in coffeescript:
//
# Behavioral 
# Iterator design pattern with Coffeescript
# Object is explicitly exported in global namespace ( for testing with console.log in the
# browser )
arr = ["begin","middle","end"]

i = 0 
len = arr.length

this.obj = 
    prev:()->
        if arr[i] is "begin"
            obj.end()
            return arr[i]
        arr[--i]

    current:()->
        arr[i]

    next:()->
        if arr[i] is "end"
            obj.begin()
            return arr[i]
        arr[++i]

    begin:()->
        i=0

    end:()->
        i=arr.length-1

//


After compiling in native Javascript:

//
// Generated by CoffeeScript 1.6.2
(function() {
  var arr, i, len;

  arr = ["begin", "middle", "end"];

  i = 0;

  len = arr.length;

  this.obj = {
    prev: function() {
      if (arr[i] === "begin") {
        obj.end();
        return arr[i];
      }
      return arr[--i];
    },
    current: function() {
      return arr[i];
    },
    next: function() {
      if (arr[i] === "end") {
        obj.begin();
        return arr[i];
      }
      return arr[++i];
    },
    begin: function() {
      return i = 0;
    },
    end: function() {
      return i = arr.length - 1;
    }
  };

}).call(this);
//

All code can be foud on my GitHub page
Happy Coding