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.