Posts

Showing posts from 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

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 Fo

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 end >> a.average => 4 In a lot of cases this approach can be useful.

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(0.8.1.2.0) 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_elemen

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 the AuthenticatedTestHelper 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...        end    end That user is loaded from the users fixtures and will act as the current logged in user. The fixtures must have something like: user_one:     id: 1     login: test     email: test@espace.com.eg     salt: 7e3041ebc2fc05a40c60028e2c4901a81035d3cd     crypted_password: 00742970dc9e6319f8019fd54864d3ea740f04b1 # test The login_as method is defined in the Authent

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 end class Survey < ActiveRecord::Base    has_and_belongs_to_many :questions end 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 end :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 w

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 #OR export SVN_EDITOR=gedit You can find more deta

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 ge

Which Programming Lanuguage Are You?

Image
Which Programming Language are You?

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 beli

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

Advanced Configuration in Firefox 3

Image
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 config

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 get_rails_casts.sh: #!/bin/bash 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 done 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

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 m

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 m

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 th

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)> da

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 app/views/users/_admin_form_column.rhtml with the following content: < dl >   < dt >     < label >is admin ?< /label >   < /dt >   < dd

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..

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: 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. Take more breaks . More breaks

Prime Numbers Generator

Image
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. downloa

MeOwns

"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.

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.google.com worth $1,740,000,000 www.sun.com worth $29,056,000 (22 years old) www.facebook.com worth $263,900,000 www.microsoft.com worth $397,440,000 www.cnn.com worth $29,440,000 www.masrawy.com worth $96,900 (8 years old)

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

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-re

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

One template file for all pages using Servlets and JSP

Image
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: mahmoud.jsp 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 param

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

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 http://server/servlet?target={user.key} 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 templa