Just upgraded to wordpress 2.
In case you encounter any problems, please be kind, and let me know at mjuneja at gmail dot com.
Archives
bookmark_borderruby code block and iterators
Code Blocks and Iterators are a very useful feature in Ruby.
An iterator is a method that executes a block of code.
Say we have a method named each
def each(array)
#do something
end
The block is specified next to the method call, after the last parameter to the method.
names=['alice', 'bob', 'charlie', 'dave']
each(names) { |s| puts s }
Our block is the code within the { } braces. (mutiple line block can be written between do….end)
We are passing an array names, in the call each(names).
Inside each() we will iterate through this array names.
def each(arr)
for i in 0..arr.size-1
yield arr[i]
end
end
All the code block iterator’s magic is done by the yield statement.
The yield statement invokes the code in the block.
The yield statement can also pass parameters to the block . In our example, the array element at position i is passed to the block. The block receives this parameter between vertical bars or pipes. (|s| in our example)
A block may also return value to the yield. The last expression evaluated in the block is passed back as the value of the yield.
Here is the complete listing of our code so far
def each(arr)
for i in 0..arr.size-1
yield arr[i]
end
end
names=['alice', 'bob', 'charlie', 'dave']
each(names) { |s| puts s }
This code will print all the array elements, as yield is called for each array element. Yield in turn invokes the code block passing it the array elements, the code block puts the element.
We could change the block code to print all the array element in upper case or in reverse.
each(names) { |s| puts s.upcase }
each(names) { |s| puts s.reverse }
What we have done so far, is actually provided builtin by ruby for various types of collections.
each is a builtin iterator in ruby which yield the elements of the collection.
To print all elements of array names we could simply do
names.each { |name| puts name }
Similarly there is a find iterator.
To print all names that begin with m, we could use
m_names = names.find { |name| name.index('m') == 0 }
m_names.each { |name| puts name }
Iterators help a lot in keeping ruby on rails code compact. I have been using them a lot, ever since i discovered them.
bookmark_borderEnd of the year questions.
Follow this link http://www.kevineikenberry.com/articles/13_questions.asp for a very thought provoking list of questions, that everybody should answer at the end of the year.
I am going to do this exercise now.
bookmark_borderRails:join table name
I just came across the naming convention for a has_and_belongs_to_many relation’s join table.
If you have tables products and categories, which have a many to many relationship, a product can belong to many categories and a category can contain many products. What would you name the joining table, products_categories or categories_products.
Rails convention says use categories_products.
Rails assumes that a join table is named after the two tables it joins (with the names in alphabetical order). If you use some other name, you would need an additional declaration.
Unless there is a very compelling reason to do so, one should stick with the convention.
Reason: For maximum productivity don’t go against Rails’ philosophy “Convention over configuration”
bookmark_borderThat time of the Year
It is that time of the year again…. when one should take stock. For me 2005 was the first time that i had set yearly goals [ read a new year resolution].
I had set many goals. They covered various fields like health, work, learning japanese, learning to swim, teaching Kuhu[my daughter] etc …
I did not achieve all that I had written down. But I made a lot of progress in all of them.
At the end of the year, I am in a position to say that for me this year was a lot better than the previous years… cos i had set some parameters to measure my performance against. I had those goals guiding me throughout the year, as i used to check my performace against them, every monthend.
I came across this quote today by Karen Lamb :
A year from now you may wish you had started today.
I am happy that I had started doing some things last year. At the same time, I want to add a few more this year.
I will spend a few hours tomorrow to write my goals for the year 2006.
I want to do so much… and breaking all of that down into smaller tasks makes it a lot easier to achieve.
bookmark_borderRyze Christmas Mixer
Attended the Ryze Christmas Mixer, at Park Balluchi on Saturday, 24th Dec, along with Pooja and Kuhu.
It was my first mixer, though i have been on ryze for a year and a half.
It was good to meet a mix of people, from various fields, software, travel, KM, media, lawfirms etc.
Had some interesting discussion with people about networking as such, pros and cons of online networking, maximizing benefits of online networking etc.
Made a lot of friends. Pooja and Kuhu also enjoyed a lot.
Kuhu got to see a lot of deers, since the resturant is located inside the Deer Park.
Here are some pictures from the mixer.
And yes the food was great 🙂
bookmark_borderThe Stockdale Paradox
I am reading Jim Collins’ Good To Great.
While reading Chapter 4. Confront the Brutal Facts (Yet Never Loose Faith), I came across the stockdale Paradox. I remembered having read about it earlier.
I googled for it and found the link .
I had read this blog post a couple of months ago, which applied Stockdale paradox to the startup phase.
The Stockdale Paradox, reinforces my belief in Perseverance and Patience. When i started my company, the only advantage (read USP) we had was “cheap programmers”. But I wanted to do more than provide services to companies because we were cheap. And gradually, at the cost of refusing lame projects, we have been able to build niche areas. I had to refuse projects, which would have added to the numbers, but would have not given the joy of programming which me and my fellow programmers now enjoy at vinsol.
This transition at vinsol, involved not only The Stockdale Paradox, but also the Hedgehog Concept, which Jim Collin discussed in Chapter 5.
I recommend this book, very strongly to all. It is a must read for Indian companies who want to rise up the value chain [I do not say that we have done so, but are better placed than where we were an year ago.]
bookmark_borderRails: Automatic Time Stamping
I tried this with mySQL. Should work with other databases too.
If you have columns named “created_at” or “updated_at” of type datetime in your database table,
Rails will automatically insert the value of now( ), in the column “created_at” when a model corresponding to the table is saved in the database. Similarly it will automatically update the value of the column “updated_at” to the value of now( ), when a model is updated and saved to the database.
“created_on” and “updated_on”, of type date, display the same functionality.
One of the basic Rails philosophy is “Convention over Configuration”, meaning that rails has sensible defaults for a lot of aspects.
If the programmer follows these naming conventions a lot of functionality in the application gets built-in by default.
bookmark_borderRails: avoid empty lines in generated html
Normally embedded Ruby code (Erb) in views that does not generate any output, leaves empty blank lines in the generated HTML code. These are embedded ruby lines in rhtml files which begin with < % and not <%=. To avoid generating these empty blank lines, end the embedded ruby code with -%>, the others will be ended as %>. The extra minus sign (-) at the end, will suppress the blank lines.
bookmark_borderRails: Escaping html entities
Many times data entered on the screen by a user, or data fetched from the db, contains less than (<), greater than (>), ampersand (&) and quotes etc. These characters have special meaning in html. And if these are passed in the view as such, they may garble the browser display.
The h() method prevents these characters in strings from garbling the browser display. The h() method escapes them as html entities.
h() method in rails does the same thing as htmlentities() does in php.
Update [17th Jan 2006] I just learnt that long name of h() is html_escape()