Posts

Adding Custom Routes for Radiant Projects

While integrating simple_captcha into the guestbook extension of radiant, I had to add a special route for the simple_captcha to work properly. Unfortunately, the routes file of a radiant project does nothing but loading the routes file from radiant gem itself: load File.join(RADIANT_ROOT, "config", "routes.rb") Calling ActionController::Routing::Routes.draw again will clear all the routes that have been defined in the gem routes file. So you have to either modify the code of the gem, or copy the code from routes.rb of the gem radiant to the projects route file. Or you can append your new routes using add_named_route instead of draw . And since the simple captcha route is supposed to be defined before radiant routes. you can manipulate the routes array as in the last line of the following sample. load File.join(RADIANT_ROOT, "config", "routes.rb") ActionController::Routing::Routes.add_named_route(        'simple_captcha',        '/...

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'},         ...

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

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

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    has_and_belongs_to_many :surveys end class Survey    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 wi...

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

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 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 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:         is admin ?            'record[admin]'%> ...

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