iOS Tutorials

After working on Android on a daily basis for almost 1 year, I started out my journey on iOS to discover the other major half of the mobile world. I followed a few different resources to help me understand different things on iOS dev, mainly Objective-C and the Xcode IDE. This blog post will include a list of tutorials I used and highlight what they are good for. This is to keep a note to myself of useful resources, and at the same time, I hope it will be useful to others too! ūüôā

  • Official getting started guide
  • About Objective-C method and function
  • An Overview of Objective-C
    • Website:¬†
    • Remarks: Good overview of Objective-C. Also explains well on memory management. Objects creation can be confusing when you’re new to Objective-C. I saw 2 ways of making objects: “NSString* string1 = [NSString string];” and “NSString* string2 = [[NSString alloc] init];”. This guide will help you demystify it and learn more about memory management in Objective-C.

Some other guides I found but yet to finish:

That’s it for now, more to be added to this list as I study! bye!



% notation in Ruby

Today I wanna share about the %notation I learned.

Any single non-alpha-numeric character can be used as the delimiter.

1.9.3-p327 :005 > %*lala lala "hehe"*
 => "lala lala \"hehe\""
1.9.3-p327 :006 > %&lala lala "hehe"&
 => "lala lala \"hehe\""

As you can see, * worked, & worked, so other symbol and friends will work too. Above example is using % notation to produce string, but % notation is actually more powerful than that, you can use it to produce array, regexp, shell command:

%Q{one\ntwo\n#{ 1 + 2 }}
=> "one\ntwo\n3"

%q{one\ntwo\n#{ 1 + 2 }}
=> "one\\ntwo\\n#{ 1 + 2 }"

=> /nemo/i

%w{one two three}
=> ["one", "two", "three"]

%i{one two three} # after Ruby 2.0
=> [:one, :two, :three]

%x{ruby --copyright}
=> "ruby - Copyright (C) 1993-2009 Yukihiro Matsumoto\n"

The post is not an exhaustive guide, but an introduction. Here’s where I copied the material from:

Take a tour to % notation through the link if you haven’t, it is definitely beneficial!

If you’re familiar with test, you can try the examples written in minitest:

It’s from this blog post:

It’s a tiring day… It’s time to get some rest! Good night ūüôā

Fixed Grid vs. Fluid Grid

Time for a short post. Today I’m looking at how to use twitter bootstrap. I took a look at the tutorial about the grid system, so I saw that they have this fixed grid system and fluid grid system. After reading through and trying hard to find out what’s their difference on the site, I finally gave up. They really looked the same. So it’s time for some googling. Ah-ha! Lucky enough, there’s a 100+ upvoted thread in Stackoverflow discussing about this topic.

In short the fixed grid will not stretch itself longer even your browser width increased; while fluid grid will stretch itself.

Fixed grid example:
Fluid grid example:

They even provide the raw html and css code to further explain fluid/fixed + non-responsive/responsive:



First experience with TDD and pair programming

Conway’s Game of Life in Code Retreat
Last weekend I went to the Code Retreat Event in Singapore. The event promotes on TDD and pair programming. In the event, we work on something called Conway’s Game of Life. It is a no player game, the game just evolves by itself from it’s initial state, and it has 4 rules, and so on… It’s easier to just show it:

Above is the Conway’s game of life coded with a special initial state that is able to reproduce “glider spaceships” on and on. If you wonder what’s a spaceship, this is a single spaceship:

The interesting thing about Conway’s game of life is the fact that it can produce interesting patterns based on just simple rules:
1. Any live cell with fewer than two live neighbours dies, as if caused by under-population.
2. Any live cell with two or three live neighbours lives on to the next generation.
3. Any live cell with more than three live neighbours dies, as if by overcrowding.
4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.

Given only 45 mins each session to code the game of life, and we’re supposed to throw away the code after every session. It’s quite impossible to finish the code (for most of the people), however the emphasis is not to complete it, but to learn from your partner through pair programming and practice TDD. Anyway I feel a need to improve on my Ruby basics, so I finish it anyway after the event, here’s my version running in the terminal in Ruby:

Screen Shot 2012-12-17 at 9.27.13 AM
A link to github for my messy (but at least working) source code:

Some thoughts on pair programming and TDD experience
In the event, I got to work with 5 different person using Ruby, C#, Java and Javascript. So here’s my experience…

I’m very new to web programming and having only 2 months experience working on Ruby on Rails, I can handle simple bug fixes without problem on a day job. In the event, whoever got to pair up with me became the more experienced guy eventually, so I get to see how they write code (of course I couldn’t learn much in a short time, but I get to see their coding habits, and get some direct feedback).

Importance of the basics of a language
While working with the experienced partner, I noticed that I’m missing something very important, which is the basics! I realize that most of them seldom refer to the documentation. For me, I must have google for something within 10 minutes. It will increase the productivity in a long run by knowing the basics well. Example, the Array class, I did not know that there’s a count() method, so I’m using ‘each’ to for counting; another example, command for generating a migration script, I have to refer to Rails Guide every single time, so I’m making it a point to remember the basics well.

Ping-pong Pair Programming
Besides, we get to practice ping-pong pair programming with TDD, where one of us writes the test, and the another writes the implementation. I realize that I learn pretty fast this way (I’m not sure if the other person learn something by teaching me thou), because I’m guided directly by an experienced programmer.
Another thing that I realize while doing ping-pong programming is that I can visualize a problem properly from the top level on what I want to build and what to expect from the outcome. I’m the one who is writing the implementation, so while looking at the other person writing the test, I can visualize the problem better and eventually, the implementation became clearer and easier. This is an interesting fact that I didn’t thought of. From now onwards, even I’m not practicing TDD, I tend to write down what I want to achieve and the expected outcome before I jump right into writing code.

Strict TDD
In one of the session, we took a challenge to practice strict Test Driven Development, which is to write implementation just enough to pass a single test at a time. This is to prevent us from writing too much code that is either not needed, or not covered by the test. The experienced developer who paired with me often ask me to STOP! and hit F8 (to run the test) while I write too much than the coverage of the test. I got a taste of how it feels like, but I’m not sure how I could do this in my daily work.

Practicing In My Daily Work?
Is pair programming worth a try in our daily job? It certainly has it’s social aspect, where someone can be your live debugger and talk to you, and get you talking to a colleague that you normally don’t talk to. Learning from an experienced guy 1 on 1, will definitely speed up the learning process.

We might be able to cover our colleague’s back if they went for a vacation and there’s an emergency too.¬†However, are 2 people working on the same thing going to decrease productivity instead? I’m not sure since I’ve never tried that yet…

Is TDD worth a try? I’m sure that TDD has many benefits, firstly, it will report any failures on any previously working code when we add in new features. Besides that, it makes us produce quality code from thinking thoroughly about how we should structure our code while writing the test. I watched the¬†Unit Testing video from Misko Hevery, and he emphasizes that the key for doing TDD is to learn how to write clean & testable code. So while we practice TDD correctly, we will eventually be able to write clean and quality code.¬†It will force us to think about the coupling of the code and write code that is easier to test.

This is some of the thoughts I have on pair programming and TDD for now after having a day of experience on an event, but I still new to all these and some of my understanding might be wrong… will blog about my new understanding as soon as I got them into my head. ūüôā

TDD is definitely one of the thing I will look into soon.

That’s it for now, good night! ūüôā

How I take mp3 out of an iPod with correct filenames

Yesterday I was trying to take mp3 out of an iPod Nano, but I realize that the file names are encrypted:

~/Desktop/iPodMusic/$ ls
AEHR.mp3 BXRT.mp3 CKZA.mp3 EAFC.mp3 GBFB.mp3 HSEC.mp3 IRUB.mp3 QPDQ.mp3

However, the mp3 tags are still there when I checked using the mp3info command:

~/Desktop/iPodMusic/$ mp3info AEHR.mp3
File: AEHR.mp3
Title: Til Kingdom Come Track: 13
Artist: Coldplay
Album: X&Y Year: 2005
Comment: Genre: Rock [17]

So I wrote a script in Ruby to rename those files according to the Title and Artist retrieved using the mp3info.

The main flow of the program goes like this

  1. Obtain the encrypted file names of the mp3 into an array
  2. Run mp3info against each encrypted file names to obtain the mp3 tags
  3. Use RegExp to parse the retrieved mp3 information into Artist and Title
  4. Rename the file name accordingly


1. Obtain the encrypted file names of the mp3 into an array

song_names_arr = `ls`
song_names_arr = song_names_arr.split
# song_names_arr now contains ["AEHR.mp3","BXRT.mp3","CKZA.mp3", ...]

Enclosing code with ` enable us to run shell command in Ruby code and return the result as a string. Now, we have the encrypted file names in array.

2. Write a function to obtain the mp3 tags information using mp3info

def obtain_mp3tags(encrypted_name)
    return `mp3info #{encrypted_name}`

# obtain_mp3tags("AEHR.mp3") will return:
#   "File: AEHR.mp3
#   Title: Til Kingdom Come Track: 13
#   Artist: Coldplay
#   Album: X&Y Year: 2005
#   Comment: Genre: Rock[17]"

3. Write functions to parse the mp3 information to retrieve Artist and Title of an mp3:

def extract_artist(aString)
    regex =*$/)
    matchdata = regex.match(aString)
    if matchdata
        s = matchdata[0].gsub(/Artist:/,"")
        puts "NO MATCH"
    return s
# extract_artist(obtain_mp3tags("AEHR.mp3")) will return "Coldplay"

def extract_title(aString)
    regex =*Track/)
    matchdata = regex.match(aString)
    if matchdata
        s = matchdata[0].gsub(/Title:/,"")
        puts "NO MATCH"
    return s

# extract_title(obtain_mp3tags("AEHR.mp3")) will return "Til Kingdom Come"

4. Now we have obtained the Artist and Title of an mp3, we can proceed to rename it:

`mv #{encrypted_song_name} "#{new_song_name}"`

Take note of the ” “, we need to enclose the new song name, if not, the mv command will give error when the new song name contains special characters such as whitespace, bracket, etc.

5. Putting everything together:

# Obtaining the encrypted file names into an array
  song_names_arr = `ls`
  song_names_arr = song_names_arr.split

  song_names_arr.each{ |e_song_name|

# obtain the mp3 information from the mp3 tags
  mp3_tags = obtain_mp3tags(e_song_name)
# check if the mp3 tag exist, if true, extract the Artist and Title
  if ((extract_artist(mp3_tags).length>0)||(extract_title(mp3_tags).length>0))
     new_song_name = extract_artist(mp3_tags) + " - " +extract_title(mp3_tags)+".mp3"
     # Rename the encrypted file names with the new song name
     `mv #{e_song_name} "#{new_song_name}"`

End result:

$ ls
Adele - First Love.mp3
Adele - He Won't Go.mp3
Adele - Hiding My Heart.mp3
Adele - That's It, I Quit, I'm Moving.mp3
Al Green - Tired Of Being Alone.mp3
Alanis Morissette - Hand in My Pocket.mp3
Alanis Morissette - You've Already Won Me Over.mp3
Amy Winehouse - .mp3
Amy Winehouse - Back To Black.mp3
Amy Winehouse - Cherry.mp3
Amy Winehouse - Our Day Will Come.mp3

Musics finally taken out with correct filenames! ūüėÄ

Behaviour Driven Design in Rails with Cucumber

Every week, the SaaS course will teach a new topic. This week, the topic is about Behaviour Driven Design (BDD). The main idea about BDD is to write the desired behaviour in plain english text first, then Cucumber will help to turn this plain english text into executable ruby code with regular expression matching (we’ll need to write the matching in regexp). By using BDD with Cucumber, we are actually designing our application from outside-in.

Developing in this way enables a developer and a (non-technical) customer to discuss the desired behaviour in the beginning and can prevent the developer to code something that is unwanted. I will walkthrough how to use Cucumber in the following of this post. I will skip the steps for installation, since it can be found elsewhere, so that I can focus more on explanation.

Introduction to the feature to be added

Let’s say we already have a site called Rotten Potatoes like below, and wanted to make the table title clickable for sorting purpose:

So we write our intended feature in a file call <filename>.feature where <filename> can be anything, examine the sort_movie.feature below, which I used for describing a clickable button for sorting in Cucumber:

Feature: display list of movies sorted by different criteria

As an avid moviegoer
So that I can quickly browse movies based on my preferences
I want to see movies sorted by movie title

Background: movies have been added to database

Given the following movies exist:
| title                                   | rating  | release_date |
| Aladdin                            | G          | 25-Nov-1992 |
| The Terminator              | R          | 26-Oct-1984 |
| When Harry Met Sally  | R          | 21-Jul-1989  |
| The Help                          | PG-13 | 10-Aug-2011 |
| Chocolat                           | PG-13 | 5-Jan-2001   |
| Amelie                              | R         | 25-Apr-2001 |
| 2001: A Space Odyssey  | G        | 6-Apr-1968    |
| The Incredibles               | PG      | 5-Nov-2004   |
| Raiders of the Lost Ark | PG      | 12-Jun-1981   |
| Chicken Run                    | G         | 21-Jun-2000  |

And I am on the RottenPotatoes home page

Scenario: sort movies alphabetically
When I follow “Movie Title”
Then I should see “2001: A Space Odyssey” before “Aladdin”

General Explanation of a .feature file

In the sort_movie.feature above, there are 3 parts, namely the feature, background and scenario. The feature portion describes about the feature that will be added, the text can be whatever without limitation. The background and scenario works almost the same except that the background will run first before the scenario. So we can think of background as giving some pre-condition to all scenarios in a feature. More information here: feature, background, scenario.

In a background or scenario, we can write multiple steps and the steps always revolve around Given-When-Then. (Note that: If I only mention scenario in later portion of the tutorial, it actually applies to background as well.) The steps will help to explain more specifically on what the scenarios is about. Note that the words underlined, such as: Given, When, Then is a special word in Cucumber, they are all used to describe steps. Given describe the state of the application, When describe the event of something happening, and Then describe what is the consequences that will happen given an event happen at a particular state.

Explanation of sort_movie.feature

The chunk of text under feature, is freestyle plain english text and it describes about our sorting feature from a point of view of a moviegoer.

I will introduce scenario before background, as it is more straight forward in this case:

Scenario: sort movies alphabetically
When¬†I follow “Movie Title”
Then¬†I should see “2001: A Space Odyssey” before “Aladdin”

The sentence after the colon in the first line is plain english. However, the When is a keyword, it is used to describe an event. We can now run ‘bundle exec cucumber‘ to execute cucumber. Now cucumber will complain this:

Undefined step: “I follow “Movie Title”” (Cucumber::Undefined)
features/sort_movie.feature:26:in `When I follow “Movie Title”‘

This is because we only write the intended behaviour, but we didn’t tell Cucumber what to do¬†When I follow “Movie Title”. So now we need to add in a chunk of code in features/step_definitions/movie_steps.rb:

When /I followses “(.*)”/ do |sort_choice|
if sort_choice==”Movie Title”

Note that this is actually ruby code. We write a regular expression to match our sentence in sort_movie.feature, so Cucumber will run this code when it encounters a matching sentence. The (.*) will find a matching word and place into the sort_choice variable. Then, ¬†we check if the sort_choice is “Movie Title”, we can further enchance this code to sort by “Release Date” as well this way.

Note the click_on method. It is a method from Capybara.¬†Capybara is a webkit that we’ll use to help us test our web applications by simulating how a real user would interact with your app. So it can help use simulate a user click on the Movie Title. The argument title_header can be the id, text, or value of the button that you want to click_on. More information about what Capybara can do: here.

Now we can run ‘bundle exec cucumber‘ again, but it will complain again, since we didn’t have a clickable button yet. So we need to add in our controller and view(not shown, just imagine the Movie Title in the top most picture became clickable).

The same goes to Then¬†I should see “2001: A Space Odyssey” before “Aladdin”. We need to add a matching regular expression in¬†movie_steps.rb:

Then /I should see “(.*)” before “(.*)”/ do |e1, e2|
aString = page.body.to_s
       if aString.index(e1)!= nil && aString.index(e2) !=nil
               if aString.index(e1) < aString.index(e2)
¬† ¬† ¬† ¬† ¬† ¬† ¬† ¬†assert false,”jr_fail”
¬† ¬† ¬† ¬† ¬† ¬† ¬† ¬†assert false,”jr_fail”

The code has nothing special except page.body.to_s will return us the html that is returned after we click_on the button. Then we use the result aString to check if the movies are arranged in order. More on page.body.


Given the following movies exist:
| title                                   | rating  | release_date |
| Aladdin                            | G          | 25-Nov-1992 |
| The Terminator              | R          | 26-Oct-1984 |
| When Harry Met Sally  | R          | 21-Jul-1989  |
| The Help                          | PG-13 | 10-Aug-2011 |
| Chocolat                           | PG-13 | 5-Jan-2001   |
| Amelie                              | R         | 25-Apr-2001 |
| 2001: A Space Odyssey  | G        | 6-Apr-1968    |
| The Incredibles               | PG      | 5-Nov-2004   |
| Raiders of the Lost Ark | PG      | 12-Jun-1981   |
| Chicken Run                    | G         | 21-Jun-2000  |

And I am on the RottenPotatoes home page

Note that the And is used after a Given, so it can be interpreted as a Given statement as well. Same as scenario, we need add in the steps:

Given /the following movies exist/ do |movies_table|
     movies_table.hashes.each do |movie|
            Movie.create movie

For the And statement, we do no need to write the steps ourselves, since Cucumber-rails in features/step_definition/web_steps.rb already provide use with this:

Given /^(?:|I )am on (.+)$/ do |page_name|
visit path_to(page_name)

Note that path_to is defined here: features/support/paths.rb.

Now, if we run ‘bundle exec cucumber‘ again, we should have all pass.

You might wonder why is it so colorful in this tutorial, that is my attempt to differentiate the difference between Ruby, Capybara, Cucumber code. I might make mistake about the coloring, but you can always check like this:

print “movies_table: “, movies_table.class,”\n”
# result# movies_table: Cucumber::Ast::Table
print “page.class:”,page.class,”\n”
#result# page.class: Capybara::Session

By knowing where it belongs to, whether Capybara or Cucumber, you can then google the correct documentation.

So that’s it, we are developing from outside-in using BDD methodology and Cucumber tools. A little bit more to graduate from the Saas course that lasts for a month. TDD will be the next topic.

Thanks for reading!

Surviving the Saas Course

I find the course pretty interesting as the homework is challenging for me but not too difficult to the point that is unmanageable. The course provide an auto grader where we can submit and re-submit our assignment making appropriate corrections. It is like solving a puzzle game.

The second homework is about adding some enhancement to a movie review website called Rotten Potatoes using Rails. Initially the site is like this:

Enhancement we need to make include making “Movie Title” and “Release Date” sortable by clicking, and the column background must be highlighted when sorted. Then we need to add in a filter on top of the page to let the user filter the movies by the ratings. After that, we need to add in session to remember the previous sorting method and ratings filter. Lastly, the homework wants us to restore those session in a RESTful manner, so that the user can bookmark the URL and go back in the future with the same settings.

After wasting off my weekend battling with the homework, I finally got it working:

Some of the things that I’ve picked up doing this homework include:

  • Writing in haml
  • Using the form_tag and receiving them from params[] from FormHelper:
  • Querying interface in ActiveRecord
  • How to route in routes.rb
  • How to use session
  • How to redirect using redirect_to and construct a URL using url_for from a session

Most importantly, it makes me code in RoR, so I can learn by doing.