Prasenjit Kumar Nag a.k.a Joy

A Developers Adventure in Coding

Seeding Data in Laravel Using Faker Maintaining Foreign Key Relationship

Faker is a great composer package for generating random data which can be used for seeding database tables for testing purposes in Laravel and other frameworks.

Suppose we have a users table and a companies table with the following structure.

1
2
3
4
5
6
7
8
9
# Table Structure
users:
    id
    username
    password
companies:
    id
    user_id
    name

Finally Moving Into Octopress

I have been planning for a long while to move my blog to Github and use Octopress from now on. Couldn’t manage time to do that. Now finally I am free from the hassle of maintaining hosting and other details and I love markdown.

From now onward this will be my new homepage and I will try to write posts regularly [ well thats a promise I always break ].

Anyway, let’s see how it goes but you know what I am very happy to finally set this up. Thanks for dropping by. :)

Facades in Laravel 4 and Static Methods Resolution

Several months ago in a blog post I saw people complaining about Laravel3’s Static methods stating Static methods are very difficult to Unit Test with and Laravel is a pile of Static API’s rather than a framework. I dont remember the Link. It said Laravel 3 is not architecturally “pure”, but it has super clean syntax.

But Laravel 4 combines both of those things. It’s extremely architecturally pure, yet maintains the same terse, expressive syntax.

Last weekend I was checking a video on Laravel 4 which was discussing about facades in Laravel 4 and I was truly amazed to see how the fancy looking static API’s are mapped into their original Classes. Laravel 4 takes advantage of Facade Design Pattern[ http://en.wikipedia.org/wiki/Facade_pattern ] which allows it to provide expressive syntax through static API’s but still keep it testable under the hood.

Taking Advantage of Implicit Looping in jQuery Setter Methods

jQuery setter methods are those methods using which we can set the value of any input field, or any attributes like width,height,classes etc and some of the setter methods are

1
2
3
4
5
6
7
8
9
10
.val(val)
.height(height)
.width(width)
.attr(name,value)
.prop(property,val)
.text(text)
.html(html)
.addClass(className)
.....
.....

and most(or maybe all) of them have a special syntax like for .width() there is

1
.width( function(index, width) )

What jQuery does for this case is, it loops over the set elements in current selection internally and pass those one by one into that callback function. And index is the index of the element currently being iterated, and width is the current width of element. And you will also get the current element as this inside that function. This syntax is useful or intended for cases when you use the .width() method on a collection of elements. I wasn’t aware of this until recently, but they can be very useful in cases. Suppose if you want to make the width of all divs in a page to half of it’s current width, you can do that easily using this syntax like

1
2
3
$('div').width(function(index,width){
   return width/2;
});

So what you return from that function will be set as new width of that element. Pretty cool, huh! You could also use .each() to iterate over the divs collection and set their width manually. But the above code is much more cleaner and maybe a little faster.

Example of some cases when this implicit looping can be useful and will help you write cleaner code.

Suppose you want to give unique id to all li’s inside a ul with id of list, you can do so the following way easily

1
2
3
$('ul#list li').attr('id',function(i){
   return 'list-item-'+i;
});

and they will get id’s like list-item-1,list-item-2,list-item-3 etc.

Another useful thing can be to trim the value in a textbox as soon as users moves away from it. You can do that like

1
2
3
4
5
$('input').on('blur',function(){
  $(this).val(function(index,val){
    return $.trim(val);
  });
});

Or say in a text field field(which takes numbers), you always want to force two decimal point in floating values no matter how many decimal points have been entered by users, you can do that like

1
2
3
4
5
$('input').on('blur',function(){
  $(this).val(function(index,val){
    return parseFloat(val);
  });
});

js

Example Fiddle: (Enter any number and click somewhere else)

[jsfiddle url=“http://jsfiddle.net/joycse06/PbKVf/” height=“400px” include=“result,html,js,css”]

There are many useful uses of this callback function in setter methods.

Suppose you have a html5 data attribute named data-bg set on all div and onclick of some button or link or on some user action you want to set that as background image of those divs. You can do do so using

1
2
3
4
5
  $('something').on('click',function(){
     $('div').css('background-image',function(){
         return '/images/'+$(this).data('bg');
     });
  });

I can show many example of useful uses of this implicit looping. This is a very helpful and often overlooked feature in setter methods which you take advantage of. :)

Lets Build a Terminal One-liner to Add All New Files Into a Subversion Repository

Those who of you have been working with subversion for a while may have noticed that when you add a number of files in different directories into an existing subversion repository you have to add each one of them from command line which is a pain.

Though the following command adds all new files recursively into the repo but it also add svn:ignored files back into the tree which is bad.

1
svn add --force *

So I was searching for a good solution today and found What I needed. In this tutorial I will to walking through the steps with explanation and finally we will have a ready-to-use one-liner, running which will add all new(untracked) files into a svn repo.

Using svn stat(or st) to check the status:  If you run the

1
2
3
4
5
svn status

#or

svn st

command from within your repo directory it will show you a list of new and modified files, I ran the command in one of my repo and the output was like this

1
2
3
4
5
?  .idea
?  application/models/book_model.php
?  application/views/find-books.php
M application/views/splash.php
?  application/controllers/books.php

The entries which have ? mark at the start are new files yet to be added into the svn repo. Lines starting with M means there are changes to be committed but the file is already in the repo. We are interested with the lines which start with ? So let’s filter the output of svn stat to find the lines which start with ? .We can use grep to do this using syntax like

1
svn status | grep "^?"

Which is telling grep to find lines which start with the character ?.  So this will out something like this for my repo

1
2
3
4
?  .idea
?  application/models/book_model.php
?  application/views/find-books.php
?  application/controllers/books.php

Now we have got the list of new files which we can add to svn repo using svn add command. But we need to remove the ? from the starting of these lines to use them as arguments of svn add . We can do this easily using the command line scripting language awk using the following  syntax

1
svn status | grep "^?" | awk '{print $2}'

we saw after using grep we had lines of this structure

1
?  application/models/book_model.php

As we are using | awk, so awk is getting two arguments first one is ? and second one is file path. So as awk is printing $2 which means the second argument, the file path. So after adding awk block we will have the following output

1
2
3
application/models/book_model.php
application/views/find-books.php
application/controllers/books.php

Which is exactly what we need to pass to svn add. Now using xarg we can pass this argument set into svn add command with this syntax

1
svn status | grep "^?" | awk '{print $2}' | xargs svn add

If you run this in your terminal all new files will be added to svn you can check that using svn stat again. Which will show that the files has been added for inclusion in remote repo in next commit.

We can make it a bit better though. Most of us use some kind of IDE’s and those IDE’s leave hidden files  for indexing and saving project specific settings. Or we may have hidden system files which we dont want to include in the repo. We can filter out the hidden files using another grep, the syntax is something like

1
svn status | grep -v "^.[ \t]*\..*"

So what is grep -v “^.[ \t]..doing here. The pattern “^.[ \t].. is matching svn status entries which have hidden files in it. If you have some idea about regular expression you can figure that out yourself, if you cant you can comment in this post and I will explain in details. And the -v option is an invert-match switch which tells grep to output non-matching files, that means files which are not hidden.

So we have got this by far

1
svn status | grep -v "^.[ \t]*\..*" | grep "^?" | awk '{print $2}' | xargs svn add

After that you can use svn stat again to make sure you are not committing anything you dont want to. Because it will add any non-hidden files in the repo. If you see that you have added a file you dont want to you can user the following command to remove that from next commit list

1
2
3
4
5
svn revert filename

#or this if you wan to remove a directory

svn revert --recursive path/to/directory/

And if you want to add any hidden file like a .htaccess then after running this command you can always use another svn add command to add that specific file or if you want you can even remove the hidden file removing grep block from the command chain.

So the one-liner you can use from now on is

1
svn status | grep -v "^.[ \t]*\..*" | grep "^?" | awk '{print $2}' | xargs svn add

This comes in handy When you add a lot of file in different directories and saves you time.

I am not very good at terminal things yet and found this snippet here.

This post is just an effort to better understand whats magic is going on in that one line.

Hope you enjoyed it. :)

Setting Up the Environment and Running Your First Rails App in Mac OSX Snow Leopard

I have been into Rails recently and found out that configuring Rails Environment is easy in Mac. So I will be sharing the steps I followed to setup the environment and running my first rails app.

Installing a C compiler: Mac OSX’s installation Disc comes with a set of developer tools which is not installed by default. So go ahead and install XCODE from the Installation DVD. It will install all necessary tools to compile and install packages from source. And we will need compiling source to install versions of ruby using RVM(Ruby version manager).

Installing RVM: Ruby Version Manager is a very handy tool while working with multiple version of Rubies. Snow Leopard comes with Ruby 1.8.7. And using RVM you can install Ruby 1.9.2 or the current stable version 1.9.3. And switching between version using RVM is very easy. So let’s jump into installing RVM. Rvm’s installation is very easy. The rvm website provides a one liner installation script to run in your terminal.

1
$ curl -L get.rvm.io | bash -s stable

Then to load the rvm you have to run the following command:

1
$ source ~/.rvm/scripts/rvm

But you are not going to load the rvm every time you start terminal. So its better to add the following file in your ~/.bashrc or ~/.bash_profile file and ~/.zshrc if you are using zsh as your default shell.

1
2
# place in ~/.bash_profile or ~/.bashrc as the very last line
[[ -s $HOME/.rvm/scripts/rvm ]] && . $HOME/.rvm/scripts/rvm

After loading the rvm script file to check if rvm is properly installed in your system run the following command in terminal

1
$ type rvm | head -n1

If you it says “rvm is a shell function” or “rvm is a function” then it’s fine and you are good to go.

Now go ahead and install an updated ruby version like 1.9.2 or 1.9.3 using the command

1
2
3
$ rvm install 1.9.2
# or
$ rvm install 1.9.3

It will take some time and that specific ruby version will be installed automatically. Now to check which version of ruby is default in terminal you can try the following command

1
$ ruby -v

It’s supposed to say 1.8.7  if you havent upgraded the default Ruby version. Now to use the newly installed Ruby you have to tell rvm to do so using the command

1
2
3
4
5
# Use which version you installed using rvm
rvm use 1.9.2
# The above command will load the environment in current terminal session
# if you want to use this as the default version in terminal all the time use --default option instead
$ rvm use 1.9.2 --default

now if you run ruby -v you will see your desired ruby version. Now let install rails gem using gem install command.

1
$ gem install rails

It will take some time and install latest rails system into your system. Now let’s create a new rails project. Move to your desired directory and run the following command

1
$ rails new blog

It will create a new rails application named blog in current directory. Now move into the new blog directory. and then run following command for bundling the gems :

1
2
$ cd blog
$ bundle install

It will take some time and install all gems required to run the application. Now start the app using the follwoing command

1
$ rails server

if you followed the previous steps properly you should see something like the following

1
2
3
4
5
6
7
Booting WEBrick
Rails 3.2.3 application starting in development on http://0.0.0.0:3000
Call with -d to detach
Ctrl-C to shutdown server
[2012-05-02 14:57:59] INFO WEBrick 1.3.1
[2012-05-02 14:57:59] INFO ruby 1.9.2 (2012-02-14) [x86_64-darwin10.8.0]
[2012-05-02 14:57:59] INFO WEBrick::HTTPServer#start: pid=81487 port=3000

It will start WEBrick (a simple  web server rails ships with itself ). And you can open your browser and point it to http://0.0.0.0:3000 and you should see the following screen

To test a full featured rails 3 app you can try this invoice app from github. This app is quite complete and even have pdf invoice generation. To install and run it try the following command  in terminal, you will have to have GIT installed. If you dont have git installed on your machine follow instructions from this page http://help.github.com/mac-set-up-git/ to install git.

1
2
3
4
5
6
7
$ git clone https://github.com/linkworks/invoices.git

$ cd invoices

$ bundle install

$ rails server

and then check the app in your browser in the following url. http://0.0.0.0:3000 you should see the app running. :) here is a screenshot of the app after you add register and add some data

Like me if you want to get fancy url’s for you rails apps through virtual hosts then follow the steps in this tutorials .

Rails by default uses sqlite as default database engine if you want to use mysql as default database then using the following command instead

1
rails -d mysql blog

Then configure your database access info in the file located at config/database.yml  and you are good to go. Though you have to have mysql2 gem installed in your system. Add

1
gem 'mysql2'

in Gemfile  in the root of your app directory and then run bundle install again

1
$ bundle install

If you have MAMP installed and want to know how you can reuse mamp’s mysql installation with rail’s apps then follow this tutorial I wrote earlier. :)

If you are using ubuntu you may try this tutorial http://blog.sudobits.com/2011/10/27/how-to-install-ruby-on-rails-in-ubuntu-11-10/

or this http://www.web2linux.com/05/installing-rails-3-on-ubuntu-10-04-lucid-lynx/

Some Sources of English Word List

I was in need of a english word list for a application and I was searching for a complete list. First and formost What they are saying around the internet that there’s no such thing as a complete list. English Language has lots of words and the count increases when you add slangs or science terms or other categories.

So I will be sharing some of the sources I have found which can save you some time if you need it at some point.

Finding one from within your nix/mac OS: If you are on a mac or any other nix distro, chances are that you already have a word list in you os. You can find it out by browsing the /usr/share/dict/  directory. In my mac which is 10.6.8 I have the following files in my /usr/share/dict/ directory:

1
2
ls /usr/share/dict/
README  connectives  propernames  web2  web2a  words

So to check I just ran a

1
cat words

and the cat command showed the full word list in the terminal. If you are sure that you dont need more than this then you can insert these words into a mysql table easily.

Login into mysql from your terminal window and select the desired database and run the following command:

1
LOAD DATA LOCAL INFILE '/usr/share/dict/words' INTO TABLE words;

I am supposing that you have a table named words. If you want the words to be inserted into a multicolumn table the run this one instead

1
LOAD DATA LOCAL INFILE '/usr/share/dict/words' INTO TABLE words(column);

Replace column with your column name which is of type VARCHAR.

I have found some other online datases too. Most of them are in excel format. You can convert excel files easily into a mysql database. The steps are:

Save the sql file in csv format(you can do that from excel save as dialogue) and then insert this into your table. I have used Sequel Pro to insert the csv into the table. If you face any problem doing this you can ask for details in comment.

And here are some other links where you can find word databases(xls,csv or sql format) too.

Wordnet

Wordlist in source forge

Puzzlers.org sources

InfoChimps

Infochimps 350000 Words

And guess what? They are all free. Try all of them to find the one thats suit’s your need. :)

English Words list are needed if you are building applications like Dictionaries or crosswords puzzle or any kind of word games.

On and Off jQuery’s New Event Binding Awesomeness

I have been using jQuery for quite a while and have used all of jQuery’s event handlers like $.bind $.live $delegate $.click etc. 

Along with the release of jQuery 1.7 , jQuery introduced two new methods for event handling. They are $.on and $.off and in jQuery.com they encouraged use of these two methods for event binding. Because no mater what other method you use like $bind , $live, $delegate jQuery is using $.on for all these under the hood. For a proof of these lets take a look at $bind , $live, $delegate definition in jQuery’s source.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
bind: function( types, data, fn ) {

return this.on( types, null, data, fn );

}

unbind: function( types, fn ) {

return this.off( types, null, fn );

}

live: function( types, data, fn ) {

jQuery( this.context ).on( types, this.selector, data, fn );

return this;

},

die: function( types, fn ) {

jQuery( this.context ).off( types, this.selector || "**", fn );

return this;

}

delegate: function( selector, types, data, fn ) {

return this.on( types, selector, data, fn );

}

undelegate: function( selector, types, fn ) {

// ( namespace ) or ( selector, types [, fn] )

return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn );

}

Now you can see that jQuery itself is using $.on and $.off for all event handling. So it’s good time to start using these new functions for event handling.

Let’s take a look at the syntax of $.on  and how we can use it as a replacement for $.live, $bind and $delegate. Here is the function definition for $.on from jQuery.com.

.on( events [, selector] [, data], handler(eventObject) )

events One or more space-separated event types and optional namespaces, such as “click” or “keydown.myPlugin”. selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. data Data to be passed to the handler in event.data when an event is triggered. handler(eventObject) A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false

seeing all these arguments it may seems a bit scary at first glance but you dont need to remember all of this. You just need to remember two basic scenarios we need most of the time.

If you need a simple event binding which doesn’t need to persist to elements dynamically added to DOM(Document Object Model) through ajax or jQuery codes then you can use on directly on the target element using the syntax

1
2
3
4
5
6
7
8
9
$(selector).on(event,handler);

//example

$('a.simple').on('click',function(){

alert('I was clicked');

});

This will be added to all anchor elements with a class of simple. But if you add new elements after the DOM is loaded this event binding wont work.

Now if you want the event binding persist to new elements added to the dom then the syntax is a bit different

1
2
3
$(document).on('click','a.complex',function(){
alert('I was clicked');
});

now I am attaching the click event to document instead of the target element. Why is that? Because I want the event binding works for new elements too.

So what will happen when user click on an element?

If you have idea about event bubbles in JS then you know that any events triggering travels from source element to its parents unless you specify other wise.

So when user will click on any element document object will get a click event and on method will check if the source of the event is ‘a.complex’ if it’s true then it will fire the handler function. Check this in the following fiddle

[jsfiddle url=“http://jsfiddle.net/GhbZv/6/” height=“400px” include=“result,html,js,css”]

Now as we are attaching the event with document as document will always exist in DOM it will work for all matching elements no matter when they are added to the DOM.

The syntax for $.off is simple

1
2
3
4
5
$(selector).off();

// to turn off a specific handler the syntax will be

$(selector).off(handler);

Though jQuery still supports previous event binding method’s, it’s good to write new event handlers using this two new methods, at least you can save a function call with this.  :)

Update:

And here goes some examples how you can convert previous $.bind, $.delegate or $.live calls

1
2
3
4
5
6
7
8
9
10
11
12
13
/* for $.bind to $.on */
/* Old: */ $(".foo").bind("click", handler);
/* New: */ $(".foo").on("click", handler);

/* for $.delegate to $.on */

/* Old: */ $("#container").delegate(".foo", "click", handler);
/* New: */ $("#container").on("click", ".foo", handler);

/* for $.live to $.on */

/* Old: */ $(".foo").live("click", handler);
/* New: */ $(document).on("click", ".foo", handler);

Making Your Terminal More Intuitive With Oh-my-zsh and Other Tools

I have started using Terminal massively since I got my Macbook back in 2010. I used it in Ubuntu but not that much. So I have always been searching for way about how to be more productive in Terminal and at the same time make it look beautiful as pass a great amount of time everyday. So I will be sharing some of the cool things I found in the internet which made my Macbook’s Terminal far better than it was before. Here is a screenshot of my current terminal window.

As you can see in the screenshot it’s looking pretty good(well at least to me). It has detected that the directory I am currently in is a GIT repo and I am in master branch. And the arrows you see in the prompt is batttery strength indicator. Pretty interesting Huh! I am using the some tools which made it so. They are:

  1. Solarized Dark Ansi Theme: It’s(link) a very popular theme and have a port for many popular editors. You can it’s homepage to check screenshots.
  2. Adding colors: Mac’s Terminal App doesn’t natively support various colors for texts. But following this  you can add more colors into Terminal.
  3. System wide Terminal: As I had to launch terminal very frequently I was searching for a solution which will allow me to fire the terminal using a keyboard Hotkey and terminal will appear above all applications. And found Totalterminal as a rescue. Now I just press CTRL(you can configure the triggering key to you preference) two times and the terminal appears immediately. And you have iTerm2 as an alternative with other useful features. Try any of them and stick with the one you like.
  4. oh-my-zsh : I have been using bash as my login(default) shell until I came to know about this project. Mac osx comes with a number of shells like bash, csh, tcsh, ksh, sh and zsh . And bash is the default shell which starts if you dont change it to something else. oh-my-zsh is a very popular project by Robby Russel. I has a magic one line installer found  in it’s github(follow the above link) page. Some of the features I like about oh-my-zsh are more intuitive command completion, command auto correction prompts, git repo branch detection, battery strength indication and many others. I found it a month ago and never looked back. :)

So based on my experience I can say that you can try oh-my-zsh. You wont be disappointed.

If you are using Mac try the more organized write up here on nettuts. If you are using Ubuntu check this Gist on how to install oh-my-zsh in Ubuntu. :)

 

Gits Stash - a Very Handy Git Feature in Some Scenario

I have started using git(a DVCS) from last month and I am liking it much. Some days back I came across the git stash command in a Stack Overflow question and was glad that git have this feature which svn doesn’t. I will be describing a scenario when git stash is very helpful.

Scenario: If you are using git it can be assumed that you are working in a team and there are other developers working on the same team. Let’s say at some point one of your team mate At some knock you on skype and ask to test a feature he just pushed into the repo. After hearing the name of the feature you find out that you two are working on the same source file and you are in the middle of something. Now you have two immediate solutions:

  1. Try committing your broken code which git wont allow as the remote branch is one step ahead and have updates on the same file, it will ask you to do git pull first.
  2. Try git pull which will trigger conflict too.

While I was working with svn I used to copy the file somewhere else and then try svn up and then accepting server’s version of the code using tf(their full). After checking the feature I would have copied the new things back from the file I copied earlier.

Using

1
git stash

we can push all current changes into git staging area temporarily. Then doing a git pull would work fine. Now we can check the new featured our peer coder added. After that we can use

1
git stash pop

to pull back the changes we previously pushed into the staging area, completing what we were doing and then commit the final changes later.

It’s one of the features of git I am liking very much. A very handy feature in some scenarios. :)