I just recently created a cookbook for wordpress.The cookbook will automatically download and set up the database for you.To get started on using the cookbook.
1.If you are using librarian just add this line to the Cheffile.

cookbook 'wordpress', :git => 'https://github.com/h0lyalg0rithm/wordpress-cookbook'

otherwise you can download the cookbook from the here and extract it into your cookbooks directory.
2.Next just add the following to the run list or to the role file.

recipe[wordpress]



Chef has really speed up the deployment process for me.It basically allows me to define the infrastructure through code which is version control and redeploy-able in seconds.Tody I will working with chef solo through vagrant.
Vagrant allows me to me create virtual machines which helps me isolate the dev environments from each other.

We start by creating the vagrant file
I will be using librarian chef to manage recipes and cookbooks.We initiate the chef repo with the following command

librarian-chef init

 

This creates the the required Cheffile which we will use to manage the cookbooks.

To get the relevant cookbooks we have to run the following command.

librarian-chef install

This will download the cookbooks mentioned in the file above into the cookbooks directory.
We then can run the knife tool to get the cookbooks installed on to the machine.

knife solo bootstrap [email protected] -p 2222

This will install the chef client on the vagrant box.It will also create a .json file in the nodes directory.Inside the this file we mention the recipes which should be run by the chef client.

Once the file is ready running the knife solo bootstrap command again sets up the lamp stack on the machine.



You must be wondering why I am writing a blog about Rails 4 even thought it came out nearly 6 months ago.This is mainly because I found some new features and missed some old ones.

One of the most obvious upgrades in rails 4 is that rails now requires ruby 1.9.3+.Which is really great as it helped clean up the core of rails.But as a developer the first change I had to make to my code Strong Parameters.

  • Strong Parameters re-enforces security in by only permitting certain variables through the params field.
  • Turbolinks:Turbolinks is a feature on rails which makes use of javascript to speed up the loading time of the website.The way it works is during the first load of the website.It loads the initial page and takes control over the links.Every time on would click on the link it would make a ajax call in the background and replace the content in the body of the html page.Thereby reducing the requests made to the server and making the website much snappy.This sounds good in theory but in practice this breaks a lot of websites as it has it own onclick and onload events which could break old code.
  • Postgres HStore:Using hstore in postgres has become even easier with the native extension for hstore data.We start with enabling the extenstion in the migration.


    We create the attr table in the images table as hstore datatype.

  • ActiveModel is another important feature in the rails where you can use regular models in rails without the persistence layer.We can even use validations just like a ActiveRecord::Base model.

 



With one of our products in our company we were given the task of building a file uploading system which would take different type of files and upload it to our server.Instead of creating a separate class for each file and having different methods to upload the file, we instead opted for a creating a polymorphic class which can be used with different classes with the has_many relation.

First we begin by creating a migration with the polymorphic relations in the database

rails g migration CreateAssetsTable

We then fill in the migration

class CreateAssetsTable < ActiveRecord::Migration
  def change
    create_table :assets do |t|
      t.string :type
      t.references :attachable, polymorphic: true
      t.timestamps
    end
  end
end

We then run the migration

rake db:migrate

This sets up the assets table with 6 columns.Id,Type,attachable_id,attachable_type,created_at and updated_at.The important columns for the polymorphic relation are the attachable_type and attachable_id.This sets up the relation between other classes and the asset class at the database level.
Next we create the model for this class

rails g model asset

This will create the model class and set us up with an empty model class.We then will in the polymorphic relation.

class Asset < ActiveRecord::Base
  belongs_to :attachable, polymorphic: true
end

Just like in the migration the polymorphic relation is the most important feature of this class.

Now that we have the asset class ready we then create other class which will use this relation.
Example:

class Users < ActiveRecord::Base
   has_many :avatars, as: :attachable, class_name: "Asset"
end

The has many sets up the has_many relation with the user model.So now the user has many avatars which refers to the assets model for the asset with type avatar.
Now that we have dealt with the polymorphic nature of the classes,It becomes very easy to add the upload module to the asset class using the paperclip gem by thoughtbot.
We add the gem to the gem file

gem 'paperclip'
bundle install -j4

Next we generate migration for the assets table to hold your new data

class AddAttachmentToAsset < ActiveRecord::Base
  def up
    add_attachment :assets, :file
  end
  def down
    remove_attachment :assets, :file
  end
end
rake db:migrate

We the add the has_attached_file to the Asset class

class Asset < ActiveRecord::Base
  belongs_to :attachable, polymorphic: true
  has_attached_file :file
end

Since version 4 of paperclip content validation is required by default.
So we also add a simple image file validation using regex

   validates_attachment_content_type :file, content_type: /Aimage/.*z/

This check if the mime type of the file contains image/ followed by the format.
Now we have a generic file upload class.



Map is another important functional paradigm where you iterate over a object and perform some changes to the original objects.
The way underscore implements the map function is pretty simple.

  _.map = _.collect = function(obj, iterator, context) {
    var results = [];
    if (obj == null) return results;
    if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
    each(obj, function(value, index, list) {
      results.push(iterator.call(context, value, index, list));
    });
    return results;
  };

The map(aliased as collect) takes the object to interate over as a parameter and the iteration function as the parameter.

_.map = _.collect = function(obj, iterator, context) {

We create an empty array to store the computation per iteration.We do a simple null check and return the empty error if null.

  var results = [];
  if (obj == null) return results;

We then check if native map is present.If it is present we delegate the map job to the native implementation.
We then run our own iterator using the previously implemented each method and then store the values into the array defined before.Finally we return the array.

  each(obj, function(value, index, list) {
    results.push(iterator.call(context, value, index, list));
  });
  return results;



Docker is a light weight virtualization tool which uses the lxc(linux containers) to run its virtual machines.
Docker uses dockerfile to create the virtual machines.To setup the apache server with php on docker is very simple.
We first create a Dockerfile with the following command

touch Dockerfile 

This creates an empty file.Lets first get the base ubuntu files for the vm.

docker get ubuntu

.This will pull the ubuntu files form docker’s servers.Now we need to add the some commands to the dockerfile for docker to run.

FROM ubuntu
MAINTAINER Suraj Shirvankar

This instructs docker to use the ubnutu base files and also set suraj as the maintainer of the dockerfile.
We then run apt-get update which fetches the package info using aptitude.We also run the apt-get install apache2 to install the apache2 server.

FROM ubuntu
MAINTAINER Suraj Shirvankar
RUN apt-get update
RUN apt-get install apache2 -y

Since we will be using php with apache we install the php.We will also need the libapache2 module for php to work with apache2.

FROM ubuntu
MAINTAINER Suraj Shirvankar
RUN apt-get update
RUN apt-get install apache2 -y
RUN apt-get install php5 libapache2-mod-php5 -y

Now that php and apache is available we can start the apache2 service.

FROM ubuntu
MAINTAINER Suraj Shirvankar
RUN apt-get update
RUN apt-get install apache2 -y
RUN apt-get install php5 libapache2-mod-php5 -y
RUN /etc/init.d/apache2 start
CMD /bin/bash

Finally you run the docker build program.

docker build -t apache2 .



Functional programming is the paradigm of programming where the functions are passed as arguments to methods and operations are performed on the function.Underscore makes use of this in a very clean and generic way.

The goal for the each method is to iterate over array or object provided as arguments in the function call.

var each = _.each = _.forEach = function(obj, iterator, context) {
    if (obj == null) return obj;
    if (nativeForEach && obj.forEach === nativeForEach) {
      obj.forEach(iterator, context);
    } else if (obj.length === +obj.length) {
      for (var i = 0, length = obj.length; i < length; i++) {
        if (iterator.call(context, obj[i], i, obj) === breaker) return;
      }
    } else {
      var keys = _.keys(obj);
      for (var i = 0, length = keys.length; i < length; i++) {
        if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return;
      }
    }
    return obj;
  };

The object/array to be iterated is passed as the first argument.A basic null check is performed and the obj is returned ie null.

if (obj == null) return obj;

We then check if the ecmascript 5's native forEach is present, if it is present we use it instead of implementing our version for each.

if (nativeForEach && obj.forEach === nativeForEach) {
      obj.forEach(iterator, context);
    } 

Javascript has neat way to check to check if a variable is a number object

3===+3

Return true

The way it works is it passes the + message to the object and === does a equality and type check.

obj.length === +obj.length

Since obj.length is a number ,we perform a check if it a number.which in turn checks if obj is array.
We then loop over each of the items in the array and pass the value to the interator function and call it.

for (var i = 0, length = obj.length; i < length; i++) {
        if (iterator.call(context, obj[i], i, obj) === breaker) return;
      }

If obj is an object we get the keys of the objects using underscore's builtin _.keys method.

var keys = _.keys(obj);
      for (var i = 0, length = keys.length; i < length; i++) {
        if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return;
      }

We call the iterator sending the values of the key in the object.



Currently i am running this blog and getting a decent amount of traffic but with increasing traffic there is increasing amount of spam hitting the server.Everyday i had to clean up the comments logs until I found Akismet.I used the free personal key and now akismet cleans the comment feed for me and it seems to work very well.Not a single false positive yet