Tuesday, December 30, 2008

A closer look at ruby gems

Have you ever been stuck at "Bulk updating Gem source index for http://gems.rubyforge.org/" while installing a gem?!Due the to the latest drop in the Internet connectivity in the middle east and my own country, Egypt, installing gems started to be like hell.. I had to wait for hours before having my library installed so I decided to have a closer look. surprisingly.. it was due to a bug in rubygems 1.0.1.

You can easily overcome this by updating to the latest gem 1.3.1 through gem update --system

Gem downloads libraries metadata about all available gems in a gem server. by default we have gem source "http://gems.rubyforge.org/" and recently i added "http://gems.github.com".gem saves this data in a cache file before it performs the required operation, so it doesn't have to download it again the next time.

Part of the code that reads the cache looks like this:

MARSHAL_FIELDS = { -1 => 16, 1 => 16, 2 => 16 }
# Load custom marshal format, re-initializing defaults as needed
def self._load(str)
   array = Marshal.load str

   spec = Gem::Specification.new
   spec.instance_variable_set :@specification_version, array[1]


   field_count = MARSHAL_FIELDS[spec.specification_version]

   if field_count.nil? or array.size < field_count then
      raise TypeError, "invalid Gem::Specification format #{array.inspect}"

That above load method is executed to load and validate the metadata of each library from the cache unless an exception is thrown. field_count represents the expected number of attributes per gem according the that gem specification version (either -1, 1, 2 but it is 16 in all cases). the keys of the MARSHAL_FIELDS hash are numbers. but the spec.specification_version is string representation of that number. so MARSHAL_FIELDS[spec.specification_version] is always nil.

Changing it to MARSHAL_FIELDS[spec.specification_version.to_i] made the rubygems work like any civilized tool :).

Thursday, November 20, 2008

Prawnto, Generating PDF in Rails Applications

Rails wiki lists a number of libraries that can be used to generate PDF files in ruby. Prawnto was very suitable for my need (generating PDF files that contain text with differentfont-size and adding some formatting). Prawn is able to generate more complex PDF documents including adding photos. You can check the installation steps online

Prawnto requires you to add code to your controller and to a .prawn layout file. There are several demos available online and can be used as guidance.

Below is an example for generating a PDF format of an article. The article has a title and an array of blocks, each block has title and content. The controller code is:

def show
   @title="My Article"
   @blocks= [
         {:title=>'Block One', :content=>'content one'},
         {:title=>'Block Two', :content=>'content two'},
         {:title=>'Block Three', :content=>'content three'},
         {:title=>'Block Four', :content=>'content four'}]
   prawnto :prawn => {
      :page_size => 'A4',
      :left_margin => 50,
      :right_margin => 50,
      :top_margin => 24,
      :bottom_margin => 24},
      :filename=>"#{@title.gsub(' ','_')}.pdf"
   render :layout=>false

In the view file of a prawnto action, we should use the pdf object. that has several basic methods to plot our PDF file. those include:

  • pdf.text("text to be written", :size=>15) #writing some text with a specific size
  • pdf.font("Helvetica") #setting font
  • pdf.stroke{line([x1,y1], [x2,y2])} #drawing a line
  • pdf.table(data_array, options) # to draw a table containing array of string arrays (data)

I used instance_eval that i described in my earlier post to create a higher level methods to increase the readibility of the view file.

pdf.font "Helvetica"
pdf.instance_eval do
   def font_size; {:title=>20, :subtitle=>16, :text=>10} end
   def write(some_text, style=:text)
      text some_text, :size=>font_size[style]
   def separator
      write " ", :text
      stroke {y=@y-25; line [1,y], [bounds.width,y]}
      write " ", :text

pdf.write "#{@title}", :title
@blocks.each do |block|
   pdf.write block[:title], :subtitle
   pdf.write block[:content], :text

Creating the higher level methods made writing the real data easier. Now you just call separator to draw a horizontal line, instead of worrying about the corresponding coordinates.

Monday, November 17, 2008

Writing Prettier Ruby Code with instance_eval

instance_eval is a method of ruby Object class that lets you pass a string of ruby code or a block to be evaluation in the scope of that object.

Through instance_eval you can actually add new methods to a particular object. This can help you write more pretty and readable code. for example, we can define a new average method for an array of numbers

>> a = [1, 2, 3, 4, 5, 6, 7, 8]
=> [1, 2, 3, 4, 5, 6, 7, 8]
>> a.sum
=> 36
>> a.size
=> 8
>> a.average
NoMethodError: undefined method `average' for [1, 2, 3, 4, 5, 6, 7, 8]:Array
    from (irb):14
>> a.sum / a.size
=> 4

With instance_eval we can add that new method here

a.instance_eval do
    def average ; sum/size end
>> a.average
=> 4

In a lot of cases this approach can be useful.

Thursday, November 13, 2008

REXML Error when running rcov

Rcov is one of the tools we use at eSpace to measure automated tests coverage for our rails applications.

By rcov through gem install rcov, I had rcov( installed.

After upgrading to the latest ubuntu 8.10, I realized that the installed rcov is not compatible with ruby 1.8.7 that i have. Rcov failed at generating the html reports with this stacktrace

/usr/lib/ruby/1.8/rexml/formatters/pretty.rb:131:in `[]': no implicit conversion from nil to integer (TypeError)
    from /usr/lib/ruby/1.8/rexml/formatters/pretty.rb:131:in `wrap'
    from /usr/lib/ruby/1.8/rexml/formatters/pretty.rb:131:in `wrap'
    from /usr/lib/ruby/1.8/rexml/formatters/pretty.rb:90:in `write_text'
    from /usr/lib/ruby/1.8/rexml/formatters/default.rb:50:in `write'
    from /usr/lib/ruby/1.8/rexml/formatters/pretty.rb:75:in `write_element'
    from /usr/lib/ruby/1.8/rexml/formatters/pretty.rb:73:in `each'
    from /usr/lib/ruby/1.8/rexml/formatters/pretty.rb:73:in `write_element'
    from /usr/lib/ruby/1.8/rexml/formatters/default.rb:31:in `write'
    from /usr/lib/ruby/1.8/rexml/formatters/pretty.rb:75:in `write_element'
    from /usr/lib/ruby/1.8/rexml/formatters/pretty.rb:73:in `each'
    from /usr/lib/ruby/1.8/rexml/formatters/pretty.rb:73:in `write_element'
    from /usr/lib/ruby/1.8/rexml/formatters/default.rb:31:in `write'
    from /usr/lib/ruby/1.8/rexml/formatters/pretty.rb:117:in `write_document'
    from /usr/lib/ruby/1.8/rexml/formatters/pretty.rb:111:in `each'
    from /usr/lib/ruby/1.8/rexml/formatters/pretty.rb:111:in `write_document'
    from /usr/lib/ruby/1.8/rexml/formatters/default.rb:28:in `write'
    from /usr/lib/ruby/1.8/rexml/document.rb:197:in `write'
    from (eval):93:in `pretty'
    from /usr/lib/ruby/gems/1.8/gems/rcov- `create_file'
    from /usr/lib/ruby/gems/1.8/gems/rcov- `execute'
    from /usr/lib/ruby/gems/1.8/gems/rcov- `each'
    from /usr/lib/ruby/gems/1.8/gems/rcov- `each_file_pair_sorted'
    from /usr/lib/ruby/gems/1.8/gems/rcov- `execute'
    from /usr/lib/ruby/gems/1.8/gems/rcov- `dump_coverage_info'
    from /usr/lib/ruby/gems/1.8/gems/rcov- `each'
    from /usr/lib/ruby/gems/1.8/gems/rcov- `dump_coverage_info'
    from /usr/lib/ruby/gems/1.8/gems/rcov-
    from /usr/lib/ruby/1.8/test/unit.rb:278

Luckily Mauricio Fernandez has provided a new version of rcov to solve this issue. It can be downloaded from his github repo or simply:

git clone git://github.com/spicycode/rcov.git
ruby setup.rb

This will install the latest rcov that will work fine

Thursday, November 06, 2008

Creating Functional Tests for Restful Authencation based websites

At eSpace we stress on having automated tests to cover our code.

If you are using Restful Authentication plugin in your rails application, You will have to bypass the authentication filter that is processed before your controller actions.Restful authentication helps you does that through the login_as() method of theAuthenticatedTestHelper module. Let me show you how.

In your functional test, login before you send the request.

   class PublicationsControllerTest < ActionController::TestCase
       fixtures :users

       def test_method
          login_as (:user_one)
          Your test code...

That user is loaded from the users fixtures and will act as the current logged in user. The fixtures must have something like:

    id: 1
    login: test
    email: test@espace.com.eg
    salt: 7e3041ebc2fc05a40c60028e2c4901a81035d3cd
    crypted_password: 00742970dc9e6319f8019fd54864d3ea740f04b1 # test

The login_as method is defined in the AuthenticatedTestHelper module, so you need to make sure you are including that module (preferably in the test helper)

Now you can create functional tests for controllers that requires login.

Sunday, September 21, 2008

has_and_belongs_to_many & Duplicate entry Error

In one of my Rails projects at eSpace, i had a Many to Many association between two models. this allowed me to look more deeply into the has_and_belongs_to_many association.

When you say:

class Question < ActiveRecord::Base
   has_and_belongs_to_many :surveys

class Survey < ActiveRecord::Base
   has_and_belongs_to_many :questions

Rails will assume there is a table questions_surveys that include foreign keys to the two entities.
So this table should be created by the following migration

create_table :questions_surveys,:id => false do |t|
    t.integer :question_id, :null => false
    t.integer :survey_id, :null => false

:id=>false will prevent the creation of the default primary key for that table.This is very important for has_and_belongs_to_many associations. as the API documentation say; other attributes in thatrelation will be loaded with the objects and will be read only, including the :id. So failing to disable the id generationfor that table will cause the loaded objects to have and "id" attribute holding the value of the id or the questions_surveys entries instead of the ids of the target entity (question or survey in our example).

That's why u may have only 20 questions but when you try "survey.questions.collect(&:id) you'll find values that are totally out of the range.

This is also the cause of the "Mysql::Error: Duplicate entry '#' for key #" entry error you'll find while adding entries. (survey.questions << question )

It is highly recommended in the rails documentation to use a real model to represent the many to many association.But if your case was just a simple two foreign keys table, use has_and_belongs_to_many, just don't forget to disable the id generation.

Sunday, August 31, 2008

Adding files to svn:ignore through command line

Recently, I have been making most SVN operations through command line. I find it more powerful, robust and surprisingly easy to use in basic operations.

svn update
svn status
svn commit file1 file2 file3 -m 'message describing the updates'

One of the things that i couldn't do at first is to mark items to be ignored. I finally realized how to do this.a directory under version control has several properties that can be set to describe the files in that directory. our property of concern is svn:ignore. We can ignore files by editing the svn:ignore property of the containing directory.

svn propedit svn:ignore .

This will open an editor allowing you to write the names of the files to be ignored. then saving and committing the directory. Note that the last parameter "." means the working directory.

You can set you favourite text editor to be used in this operation by setting the environment variale

export SVN_EDITOR=vim
export SVN_EDITOR=gedit

You can find more details on svn commands by typing "svn help"

Monday, July 28, 2008

Building interactive web pages using AJAX and RJS

When we talk about interactive web applications, AJAX is one of the most important technologies. Rails provides an easy way to use Ajax in your web site through RJS. RJS helps you make and ajax request and have several page elements updated correspondingly.

Implementing Ajax requests using RJS is a simple matter of doing the following:

  • Include the requried javascript files.
  • Use the right rails tags to launch an ajax request.
  • Declare that your action in the controller can respond to rjs.
  • Define the rjs response (the changes to the DOM).

Any rails application has the javascript files (prototype.js, effects.js, dragdrop.js, controls.js, application.js) by default. All you need to do is to include them in your layout file by adding:

<%= javascript_include_tag :defaults %>

Rails provide 'remote' alternatives for its link and form tags

  • link_to_remote vs link_to
  • form_remote_for vs form_for and
  • form_remote_tag vs form_tag.

Using the remote alternative will cause the html tags generated to have a new AjaxRequest call;
so when u specify:

<%= link_to_remote "Some text", :url => {:action=>'action_name'}%>

This will cause the new anchor tag to have an onsubmit attribute with the required ajax call to the action.

You need also to declare that the controller method responds to ajax by adding the following part to it. (You can also add format.html of action can be called with a normal request)

respond_to do |format|

Finally, define the changes in the DOM (reponse) in the a new .rjs file in the views directory

page.replace_html :element_id, 'new html replacement'
page.insert_html :bottom, :element_id2, 'new html element below the element_id2 element'
page.insert_html :top, :element_id3, :partial => 'partial_name' , :object=> @object

Ryan Bates provided a nice demonstration on how to make Ajax calls with rjs in his rails casts.

Sunday, July 20, 2008

Rich Text Editors for Radiant CMS 0.6.7

If you are creating a radiant project that will have content edited by non technical people, you'll probably need a rich text editor to be available in your website.

There are several Radiant extensions available for that purpose including TinyMCE, Wym Editor, and FckEditor.

Well, TinyMCE is a very nice text editor, but it seems it is not yet compatible with Radiant 0.6.7. I managed to installed it successfully following the installation instructions, I can see it listed among the extensions in the administration area, it is there among the filter when editing the page, but the toolbar simply doesn't show up.

FckEditor worked very smoothly with me. the Installation inctructions are simple and direct

RAILS_ROOT$ git clone git://github.com/djcp/radiant-fckeditor.git vendor/extensions/fckeditor
RAILS_ROOT$ rake radiant:extensions:fckeditor:update

Fck Editor started just fine after installation and working very smoothly with the new radiant version.

As for Wym Editor, i believe the installation instructions should have been more clear. it should be as follow:

RAILS_ROOT$ git clone git://github.com/jomz/wymeditor-for-radiant.git vendor/extensions/wym_editor_filter
RAILS_ROOT$ rake radiant:extensions:wym_editor_filter:install

The first git clone command wasn't listed in the readme file. when i cloned the repository it was downloaded the name wymeditor-for-radiant it took me sometimes to realize the mistake i have made by having the extension directory with an invalid name. However, i fixed my mistake and had it prepared.Then i faced another issue. the editor interface is not having the default english language.Digging shortly i realized it is loading the strings from the nl.js file which has danish language or something, insteal of loading en.js. I'm not sure yet if it was an installation problem or a bug on their side. Fck Editor was more prettier for my application so i didn't spent a lot investigating here.

Tuesday, July 01, 2008

Traffic Jam Parking Game

There are many flash games online. I liked this one a lot.
The idea is simple, move the cars around and unblock your path home to your caring wife.

enjoy it

Wednesday, June 25, 2008

Advanced Configuration in Firefox 3

Everyone can customize a lot of options in Firefox through the "Tools>Options" or "Edit>Preferences" menus.

Well the other way is to make customizations through the advanced configuration interface by typing "about:config" in the address bar. You will see the interesting warning message. well, just be careful while you are about changing values.

Here you can make a lot of configurations like:
  • browser.download.manager.closeWhenDone set it to true to automatically close the download window when the download is complete
  • browser.download.dir sets your download directory
  • browser.urlbar.maxRichResults sets the number of suggested URLs that appear when you start typing in the address bar
  • zoom.maxPercent and zoom.minPercent to alter the maximum and minimum limits of zooming

You can find some configurations explained at ghacks, eriwen's blog and many other locations online. most configurations are self explanatory though.

Using the advanced configuration can be preferable to some people, specially software developers like myself. I already liked it.

Tuesday, June 24, 2008

Downloading Rails Casts

Rails casts is hosting Ruby on Rails video tutorials. It explains a lot of tips for development and how different rails components work. I highly recommend it for rails starters.

I wanted to download all the previous episodes, that needed me to open the page of each episode, find the link for the mov file, and click save as. So i created a bash script to visit the links of the episodes and do the job automatically


for ((i=$1;i<=$2;i+=1)); do
wget http://railscasts.com/episodes/$i -O- | grep -oi 'http://media.railscasts.com/videos/[a-z_0-9]*.mov' >> links
while read LINE ; do wget "$LINE" ; done < links

Now the script can be used to download any range of episodes. below i'm calling it to download episodes from the episode #1 to episode #115

./get_rails_casts.sh 1 115

Sunday, June 22, 2008

Setting Up RubyOnRails Development Environment on Ubuntu 8.04 Hardy

I started a new fresh installation of Ubuntu 8.04 (Hardy).. i needed to prepare my machine for RubyOnRails development. Below are the steps i need to make:

Installing Ruby, Rails, MySQL

Install MySQL

apt-get install mysql-server mysql-client 

Install Ruby (1.8.6) and gems

apt-get install build-essential ruby irb rdoc ri ruby1.8-dev libzlib-ruby libopenssl-ruby1.8 rubygems libmysql-ruby1.8

Update gem

gem update --system
rm /usr/bin/gem
ln -s /usr/bin/gem1.8 /usr/bin/gem

Install Rails & Mongrels

gem install rails mongrel mongrel_cluster

Installing rails 1.2.5 (needed in my project)

gem install rails -v 1.2.5 --include-dependencies

Move the mongrel_rails, rails and rake to the /bin directory

ln -s /var/lib/gems/1.8/bin/mongrel_rails /bin/
ln -s /var/lib/gems/1.8/bin/rake /bin/
ln -s /var/lib/gems/1.8/bin/rails /bin/

This makes us done with the basic ruby and rails installation.

Installing RMagick

Rmagick is an image processing library that is needed by some rails projects (including mine). Remove conflicting packages in case there were previously installed, install the right version of the libraries and then get rmagick through gem

sudo apt-get remove --purge librmagick-ruby-doc librmagick-ruby1.8
sudo apt-get install libmagick9-dev ruby1.8-dev
sudo gem install rmagick

Downloading and Installing Aptana Studio

download the compressed distribution of Aptana for Linux from aptana download page

Aptana is an eclipse based IDE. We need to install JRE in order to run aptana

sudo apt-get install sun-java6-jdk
sudo update-java-alternatives -s java-6-sun
sudo update-java-alternatives -s java-6-sun

sudo vim /etc/jvm

add this line at the top of the file


sudo vim /etc/profile

and this line at the beginning of the file

export JAVA_HOME=/usr/lib/jvm/java-6-sun

Installing RadRails

  • start aptana studio
  • navigate to "help" > "software update" > "find and install"
  • select "search for new features to install" and hit "Next"
  • select "Aptana: RadRails Development Environment and click Next
  • follow the wizard to the end of the installation then restart aptana studio

upon restart, if you get the "unable to detect ruby install" error, you need to setup the ruby interpreter in aptana

  • Open "Window" > "Preferences"
  • goto "Ruby" > "Installed Interpreters"
  • click "add"
  • set the "RubyVM home directory" to "/usr/bin" and the name to anything ("ruby1.8" would be fine)
  • click "ok" and select the new added interpreter

This should make the machine ready for developers to start being productive.

Monday, June 02, 2008

Heads Up With Radiant CMS

Radiant is an open source RubyOnRails based Content Management System, designed for relatively small websites. One of the nice things about radiant is that it the templates themselves are stored in the database like ordinary content, making all interactions with the site once it is deployed through the administration interface.
In radiant, a page can be composed of several named parts. Parts of the interface that is shared among several layouts (like navigation bar, footer, header) can be stored in snippents. Using snippets, layouts and page parts helps the site creators to elegantly build and maintain their website.
Some features that is beyond a CMS, like having a page that sends emails or a form that stores data somewhere, can be obtained through radiant extensions.
let's start a new radiant project:

first you need to install the radiant gem
gem install radiant --include-dependencies

then create a new radiant project specifying the database engine used.
radiant --database mysql mysite

Now you have the project created.
Create a new database and set the database connection paramaters in the database.yml, then bootstrap
rake development db:bootstrap

This will start creating all necessary database tables and relations. then it will ask you for the administrator credentials.
Create the admin user (press enter for defaults).
Name (Administrator):
Username (admin):
Password (radiant):

After creating the admin account you will be asked about the type of database templates to be used.
Select a database template:
1. Empty
2. Simple Blog
3. Styled Blog

  • The Empty project template creates a project with no initial pages at all. once you start the server and try to open the site, you will be forwarded to the administration login page. You'll need to create all layouts, snippets, pages from scratch
  • The Simple Blog template creates a simple plain text website with blog structure set and two simple posts and with nearly no stile at all.
  • The Styled Blog template creates a project that has the blog part setup like the previous type. but it is more rich with stylesheet and nice display. Of course you will need to override the current initial implementations with you own.

After you created the project. start the server
ruby script/server -e development

Then check the new created website at http://localhost:3000
and check the administration interface at http://localhost:3000/admin

Yo can check the demo at radiant website to see a real working example.

Tuesday, May 27, 2008

Introducing BDD with RSpec

Behavior Driven Development (BDD) is an approach for software development combining the advantages of Test Driven Development and Domain Driven Design. It helps the team of the project focus on the exact requirements of the client in a verifiable manner.

In TDD, we had acceptance tests that verify the correctness and completeness of the feature once they pass. Those tests are written by the developers at the beginning of an iteration. A weak point though is that those tests were written in a programming language (java, ruby, ..) nothing that the customer can understand. BDD introduces a common vocabulary among all people, that is simple text, something that even the customer can understand and write.

RSpec is a ruby framework that helps with the implementation of BDD. It is really an interesting project.
RSpec started with what they call now the "spec framework", this framework describes pieces of the application model through by specifying characteristics and actions that can be verified through the code. check the example at the rspec site

The second part of rspec is called the "story framework".. the story framework is the same old rbehave project that was started by Dan North back in June 2007. Five months later, rbehave joined rspec and became the story framework of rspec.

The story framework enables the team to document user stories in simple text format written in a specific structure. A story is described and a set of scenarios are written to describe how the system should behave. The scenario is composed of several steps that can be programmatically implemented, so we end up in having an executable user story.

The example at the rspec homepage shows how this framework works.

the scenarios are written using a small set of keywords "Given, And, When, Then" that describe the steps of the scenario. "Given" declares the steps that describe the context, it can be used to setup that context for our test. "When" describes the action that is made. "Then" describes the expected results or expected final state the system after the action, "Then" steps implementation usually have the "actual.should ==expected" lines that are very similar to the ordinary assert instructions in most testing framworks.

One important point to consider is that the Scenarios should be written in a very specific manner. The developers won't be able to implement steps of abstract nature. for example:
when you are writing scenarios that describe that validation of a user model

DO NOT write:
Given the user has some invalid values
When the user submits
Then the user should be invalid

Instead, write:
Given the user entered his email as invalidemail
And the user left his name blank
When the user submits
Then the user should be invalid

David Chelimsky, one of rspec core team shows how to write plain text stories having the implementation of steps in a separate file which makes the stories look more elegant.

Monday, May 19, 2008

Posting Messages Using Jaiku API through Ruby console

Jaiku is considered a nice communication method among a group of friends or colleagues in a small company or so. One major strength of jaiku is that it has a lot of notification methods about updates. users can receive notifications through sms, IM or throught jaiku website.

I wanted to take a look at jaiku API. so i can use it in any application to send notifications to the rest of my colleagues. the user uses his username and API key to authenticate operations through the API

Jaiku provides two interfaces that can be used to read/write jaikus. the XML-RPC and the JSON interface. xmlrpc behaved little strangly always responding with "XML-RPC server accepts POST requests only." even when i'm sending POST requests.

i managed to use the json interface though

just send a post request to api.jaiku.com/json with the parameters(username, api key, method, message)

throught Ruby's irb
i can send a note by typing:

irb(main)> require 'net/http'

irb(main)> data = 'user=username&personal_key=999999999&method=presence.send&message=#channel This Message goes to everyone on that channel'

irb(main)> http = Net::HTTP.new('api.jaiku.com')

irb(main)> result = http.post('/json',data)

irb(main)> result.body

=> "{\"status\":\"ok\"}"

I believe this can be a valuable feature for some websites

of course you can make similar functionality through a simple html page with the following code

< form action="http://api.jaiku.com/json" method="post">
      Message to Jaiku< input name="message" type="text" value="">
      < input name="user" type="hidden" value="username">
      < input name="personal_key" type="hidden" value="fd36a832c09ed8765">
      < input name="method" type="hidden" value="presence.send">
      < input type="submit" value="send message">
< /form >

Whatever the way u choose to do this.. an important note is that you have to use the POST HTTP method. and you have to use the method=presence.send of course with your username and personal key

Wednesday, May 14, 2008

Overriding input components in active scaffold

One of the wonderful facts about Rails is that most stuff you need is already created for you, keeping you free to customize as you want.

ActiveScaffold is one of the most powerful and widely used plugins in rails projects because it simply provide you with a complete CRUD for your model with minimum coding.

The default view of the active scaffold is adequate for some applications, but not the most pretty. so is the input types used for the model attributes. Active Scaffold team helps us by providing and easy way to customize by overriding active scaffold defaults.

In my application i had a boolean attribute "admin" in my model "user". that was showed as a drop down list having the values of true & false. Pretty ugly.

I used partial form overrides to make it the more logical check box by adding
with the following content:

< dl >
  < dt >
    < label >is admin ?< /label >
  < /dt >
  < dd >
    <%=check_box :record, :admin, :name => 'record[admin]'%>
  < /dd >
< /dl >

Now when i create a new user, i can see a check box at the admin field. instead of the old ugly dropdown list.

A glimpse of fizo

Sitting there at the tram on my way to work, when i saw fizo.. a 70 years old fizo.

Well, it wasn't our own fizo himself. It was an old man who seemed to be like a future image of fizo. He was thin, had a white mustache and mixed (white, gray) mid long hair on the sides of his head, wore black framed glasses and clean tidy outfit, and moreover, his fingure nails looked something close to those of foze.

just wondering how would i look like if i was to reach that age..

Thursday, May 08, 2008

16 Ways to Keep A Razor- Sharp Focus at Work

I came across this nice post about focusing at work, i'd like to share..

Focus is something of a novelty these days. We’ve got cellphones for texting and calls, IM, Twitter, Email, RSS feeds, Facebook, Myspace… the list goes on and on. If you don’t have ADD before you start working online, it seems it’s almost inevitable thanks to these inputs. If you’re a web worker who uses the Internet for the majority of the day, you’re especially at risk for losing focus.

Focus is something that must be fought for. It’s not something that automatically switches on when you want to. You have to make sure your surroundings are perfect for working if you want to be focused. Here’s a few ways I’ve found this to work:

  1. Use offline tools. Paper products, pens, and other physical tools are a Godsend for those of us who have a hard time focusing throughout the work day. They’re so simple that we can use them quickly, without having to worry about becoming distracted.
  2. Take more breaks. More breaks = More productivity. It may sound wrong, but it’s true. Breaks allow us to re-group our thoughts and focus for the task at hand. They also keep us fresh so that we don’t end up burning out after only a few hours work.
  3. Smaller tasks to check off. When you’re planning your day, make sure that your “action steps” (aka items in the checklist) are small actions. Instead of “Paint living room”, try breaking it down into many tasks, like “buy paint, buy rollers, pick colors” etc.
  4. Keep a steady pace. Don’t try to do to much. Keeping the pace manageable allows you to keep your focus. Unfortunately, people can confuse this with “Work till you drop without breaks”. See number 2.
  5. Keep a daily “purpose” card. It’s pretty easy to get lost staring at the computer all day long. We’ll find rabbit holes to wonder down (ie. Youtube, Myspace, etc.) if we’re not careful. Having your daily purpose card gives you clarity and a reminder as to what you’re doing today.
  6. Develop the mindset that the computer is only a tool. It’s easy to try and use the computer for too much. At its core, the computer is merely a tool (albeit a freakin’ awesome one) that allows to do work more efficiently. If we’re using it as something more than that, (like as a solution for your life), you’ll ultimately fail. It’s like trying to eat a steak dinner with only a spoon.
  7. Plan your day to the T. If you’re finding sporadic periods of laziness throughout the day, it could be because you don’t take enough breaks (see #2), and you don’t have the day mapped out as efficiently as you could. Make sure your list of todos has lots of small, actionable steps that can be done quickly. This will gives a really satisfying feeling when you’re crossing things off your list like crazy.
  8. Notice your lazy routines. Everyone has recurring lazy spots throughout the day. Plan to have your breaks for those times. You’re going to be lazy then anyway, right?
  9. Plan the night before. Planning the night before is a great way to really get focused on the next day. “Sleeping” on your tasks and goals for the following day can really help your mind expect what’s going to happen the next day. Essentially, you’re preparing your mind for the following day. Advanced focus.
  10. Turn off extra inputs. These are IM and email for me, but we all have our Achilles heel. Completely turn off any distracting piece of technology that you own. Every one of these inputs tries to steal bits of your focus. And they won’t rest until they do.
  11. Set time limits for tasks. There’s no motivation like a deadline. Giving yourself real deadlines is a great way to stay motivated and focused on the task. Given the fact that we human are natural procrastinators, it’s no surprise that we’ll take as long as we’re allowed to finish something. Setting real but attainable limits is a great way to keep the project humming, so to speak.
  12. Keep a journal of what you did throughout the day. I like to use a moleskine notebook for my lists just so I can go back and review it every now and again, to see what I’ve done. Knowing how far you’ve come can keep you sharp and motivated to finish.
  13. Use programs to track where you spend your time. This is a real eye-opener. Knowing just how much time you spend every day/week/month on a certain site or with a certain program can quickly show you where your priorities lie. I recommend Rescue Time, but there are many others.
  14. Visualize the day in the morning, before it starts. A little pre-work meditation on the day’s events is a great way to start the day off focused and productive. Don’t worry about a full 30 minute session, a quick review before you start the day is fine.
  15. Start the day right. Starting the day with a good breakfast, some quiet time and/or exercise is a great way to set your day up for success. Sounds like a cliche, but it really works.
  16. Clean yourself up. It’s why my track coach in high school made us dress up for big races: you perform the way you feel. And if you feel polished, groomed and ready, you’ll be more likely to be productive. For me this is just taking a shower, brushing my teeth and putting on casual clothing. I used to work all day without taking a shower in my PJ’s, but I never got much stuff done. Let’s be honest here… if you’re dressed really casually, odds are you’ll be working really casually. Just taking the time to clean up a bit before you buckle down for the day is never a bad idea.

For more from Glen, check out his great productivity blog, LifeDev. He’s also the co-owner of the LifeRemix blog network.

Sunday, March 30, 2008

Prime Numbers Generator

did u know that 34136029 is a prime number?!!
well.. that's what i recently realized :)

I thought of writing a piece of code for that purpose.. wondering how far i can get.

The idea of the code is simple
We know that 2 and 3 are prime numbers
the code checks every following odd numbers to be prime or not.

To verify a prime number, the number divisibility by the prime numbers generated so far is checked. (29 is a prime number.. because it id not divisible by 2, 3, 5, 7, 11, 13, 17, 19 nor 23)

We only need to verify divisibility against the numbers smaller than or equal to the root of the number in hand. (We needn't check the divisibility of 33 with 11, as we already must have found out it is divisible by 3)..

I did not want to go with the mathematical root evaluation as i am not sure about its load. I used bits handling instead. the root of a number uses at most half of the number of bits that the original number uses.

i only made a naive java implementation so far. download the jar file and try it yourself "java -jar prime-generator.jar"

Here i explain the implementation

Generating Primes
This method starts by marking 2 and 3 as primes.. then check the rest of the odd numbers until the upper limit is reached (this is a value passed as a parameter to the class OR the largest number that can be held in a long primitive type)

The longest long value can be found my shifting 1's to fill the bits of a long variable before it converts to a negative number.

to verify a prime number, the number in hand is compared to the identified prime numbers that are less than the assumed root limit.

Instead of evaluating the mathematical root. i used that fact that the root of a number will use at most half the number of bits used by that number.

the output for the program is

1: 2
2: 3
3: 5
485785: 7143883
485786: 7143887
485787: 7143911
485788: 7143931
485789: 7143959
2097148: 34135967
2097149: 34135999
2097150: 34136009
2097151: 34136021
2097152: 34136029

the code generated 2097152 prime numbers.. starting with 2 and ending with 34136029.

i think i can go farther...

it was stopped by ArrayIndexOutOfBoundsException. there must be a way to get a larger array... or i have to find another way to track the numbers instead of having them in memory.

Wednesday, March 19, 2008


"Expressing yourself through your belongings"

This is the main idea of eSpace new product, meowns. It is still currently a beta version. The main part of MeOwns is the widget. you can see that in the right side of the my blog.
well.. simply, that's me; owner of those books, that mobile device, that nice FZ3 digital camera and those cats. does that tell u anything about me. well, i guess yes. at least an impression.
You can ask me about my experience with this stuff too. We can share ideas, thoughts and wishlists. i can find other FZ3 owners or other cat owners, maybe we can be friends.

It is much interesting. i believe the meowns team did a great work here.

You currently need to be invited to make your meowns account, so leave me a note with your email if u want to try.

Thursday, March 13, 2008

Firebug on Firefox 3.0b4

i had installed the beta firefox 3. it seems nice.. and less starving for memory so far (the thing i really hated in FF).
One issue i had is that most addons aren't yet compatible with the new FireFox. including firebug. As a Web Developer, i cannot imagine being with no FireBug available. Firefox 3 couldn't not find a compatible update. and when u search for the addon manually on mozilla addons. u get the old one that is compatible with FF2.

Fortunately. i was able to locate FireBug 1.1 beta that is compatible with FireFox 3. i guess it was not added to the addons list because it is still a beta...

find a website value with dnScoop

I came across dnScoop, an online tool to determine the estimated value of a website depending on several factors. Factors include Domain Age, Page Rank, Inbound Links, Traffic Rank and others.

The power of dnScoop is that it interacts with several other domain lookup tools out there. u only need to provide the domain that you are interested in. unlike other website value calculators like websitebroker calculator and glurk that requires u to enter some data (monthly traffic, and Alexa Page Rank,....)
according to dnScoop this is the estimated value for some websites
www.yahoo.com worth $1,884,000,000
www.sun.comworth$29,056,000(22 years old)
www.masrawy.comworth$96,900(8 years old)

Sunday, March 09, 2008

God's Greatest gift...

102 days Ago Allah gave me the greatest gift i ever had... my young Hazem..

i like it when i sit with the 3 month old fellow... talking to him and watching his responses... the best of all.. is that i can see he is totally focused with me in the conversation... his smile is priceless..

i'm really amazed how he made me feel

Monday, March 03, 2008

Using maven with eclipse

As i first started using maven for my projects, I used to add the maven plugin to eclipse. The plugin makes you able to mark a project as "maven enabled". This adds the library maven dependencies to the classpath of the project so the dependency libraries can be visible to your classes.

As i moved further, I found a better way dealing with maven projects using eclipse; maven eclipse:clean and eclipse:eclipse goals.

the goals enables you to make all the configuration and settings through command line which is more powerful and stable. Actually i now never created a new project inside eclipse. It is better to created it outside using maven. Then through eclipse:eclipse u create eclipse project settings files that is ready to be imported to any running eclipse instance.

M2_REPO variable that points to the local maven repository. The pretty thing is that you can add that variable to an eclipse workspace through mvn -Declipse.workspace={workspace-path} eclipse:add-maven-repo

To put things into order. for better use of maven and eclipse:

Setup maven repo variable for the eclipse workspace

mvn -Declipse.workspace=D:\java\eclipse-workspace eclipse:add-maven-repo

Create your new maven project through command line

mvn archetype:create -DgroupId=com.mycompany -DartifactId=MyProject -DarchetypeArtifactId=maven-archetype-webapp -Dpackaging=war -Dgeneratepom=true

Change the working directory to that of the new project and setup eclipse project files

mvn eclipse:eclipse

When you edit your pom file to add/remove dependencies you must resetup the eclipse project files through

mvn eclipse:clean eclipse:eclipse
and then do not forget to refresh ur project in eclipse :)

find more about maven with eclipse

Thursday, February 14, 2008

Troy Quotes

"If they ever tell my story, Let them say that i walked with giants.
Men rise and fall like the winter wheat, But these names will never die.
Let them say i lived in the time of Hector, Tamer of Forces.
Let them say i lived in the time of Achiles." Odysseus

Tuesday, February 05, 2008

One template file for all pages using Servlets and JSP

One of my recent tasks was making a new skin for one of our websites. the site had a common header, left side area and right side area that are to be shared among all pages. we used to include file for "header", "left side", "right side" in each of the pages.. it wasn't that pretty i know.

I wanted to think of something better where i can define the template in exactly one file and i do not have to include that file on every new page i add. something pretty much close the RubyOnRails "<% yield %>' directive to import the page content inside the template. i finally managed to do it.

I'll use two simple pages to illustrate the concept:


and index.jsp

what we want is to have each of the two pages displayed in a layout where is one header, banners and so. which will look like the following.

I was able to do this using a servlet that intercepts the request. and loads the template jsp file and pass the desired page to as a parameter to be included.

The template file is called template.jsp will look like:

The only line that matters in the template code is where we make the jsp:include page="<%request.getParameter("targetPage")%>"

The servlet intercepts http requests and loads this template using RequestDispatcher and passes the original desired page as a parameter:

The Servlet and servlet mapping in web.xml will look like

A note to be mentioned is that I had to configure my template to be initiated with requests to html pages (i can choose to work on any extension except jsp). When I configure my servlet mapping to be associated with jsp URLs, i get stuck in an infinite loop as since including the page inside the template results in a new jsp request.

The idea is simple. You are free to create your own template and to work on any file extensions in the url, but you have to specify a type other than jsp to avoid the infinite loop trap.

Bon appetite

Monday, January 28, 2008

Bride.. a writer :).. congrats

finally her talent in writing is being rewarded. Bride (Ghada) has issued her first book out of her blog posts. for several years we have been enjoying reading her stories and her ironic accent. those are currently available in the new book that can be obtained through the book fair in Cairo.

Heads up to Ghada.. congrats

Wednesday, January 09, 2008

URL encoding special characters

i had a weird bug yesterday that consumed a bit of my time.
we have that we have an email that is sent to the user of one of our sites, with a link leading him back to his session (we add some key of the user to the link for that purpose). anyway.. we use a mail template.. a jsf page... all we need to do is to read that page (html generated for that jsf page) and replace some keywork with that parameter value
i had the link in the following format
and i should replace that "{user.key}" with the actual value of the generated key.
this approach have been working fine for quite a while for that feature in several of our sites.
However, recently i was reported that the link was broken and leading to the error page.. as i investigated the matter i found that the link in the emails is
http://server/servlet?targetKKKKKK such that (KKKKKK is the key value)... the equal for some reason was missing.. pretty odd.

i checked the content of my template file.. the equal was there.. mmm..
after a lot of trials and debugging.. i was able to isolate the part where this problem was generated.
in reading the template we read it as an html resource on the web. not as a file. that's how to get the generated HTML and not the jsf code.

i tried http://server/templateURL.faces and voila... the problem was there..
for some reason the server dropped the equal character when generating the link. going little deeper i realized it is not the equal.. is it is the letter directly before the curly brace "{"... whatever u put there is being eliminated.

"Some systems can possibly modify these characters" that's was mentioned in some site describing a set of unsafe characters in URL encoding. maybe our system just decided to interpret the left curly brace as a back space..

my proposed solutions was either to use another stable character.. or to add another space and handle that when reading and parsing the template. (using "target=={" and when parsing the template i reverse it back if it is still there..)
it is a silly quick fix.. but it is the one that makes me backward compatible specially that i'm changing a code that is used by several of the sites.