Friday, March 21, 2008

Debian parodies, Iceweasel and Icedove

Few days back while going through an article about new Knoppix 5.3.0 I came upon the two familiar but unheard tools i.e. Iceweasel and Icedove, both followed by the names Firefox & Thunderbird 2.0 in brackets respectively. For a moment I began to muse about when did these two names came into existence for the two most popular open source internet tools. After a little googling and going through wikipedia I got my answer.

Mozilla corporation holds trademark for name Firefox and its logo. Unofficial releases of Firefox can’t use the same unless they use the binaries supplied by Mozilla or have special permission. If none of the two conditions satisfies then one must compile the source with an option that gives the generated binaries code-name of the release version of the Firefox on which it is based, and which doesn’t use the official logo or any other artwork.

Iceweasel and Icedove are the re-branded version of Firefox and Thunderbird maintained by Debian. Debian guidelines, commonly known as Debian Free Software Guidelines, states that all parts of Debian distribution should be modifiable by those who use it. This conflicts with the licensing and strict guidelines of Mozilla Trademark Policy. As a result Debian forked the development of Firefox & Thunderbird projects with new names together with some extra features and a logo which is freely licensed.

Saturday, March 15, 2008

Carriage Return (CR) & Line Feed (LF)

Today while playing with `od` - a command-line tool to dump file data in octal and other formats - and looking at 012 (octal code of \n) it just came to my mind to find out the difference between carriage return (\r) and line feed (\n) characters and how do they date back in history. I got my answer from the very first attempt in Google which directly led me to Yahoo answers.

The two characters emulate the two main actions in typewriters. Carriage-Return which moves the cursor back to the beginning of the line corresponds to the moving of typewriter’s carriage to the initial leftmost position, whereas Line-Feed which move the cursor to the next line corresponds to the rolling up of paper by one line. The combination of both i.e. CR-LF were initially used in Teletypewriters to move the print head back to the beginning of new line.

Even though the two still performs the same action in standard output and printers, not all operating systems use both of them. *nix based systems use \n, Mac uses \r, whereas Windows uses both \r\n. This is a reasons why *nix text documents look weird in windows.

Wednesday, March 5, 2008

Some common abbreviations to remember

GDK GIMP Drawing Kit
GIMP GNU Image Manipulation Program
GNOME GNU Network Object Model Environment
GNU GNU is not Unix
GTK GIMP Tool Kit

Monday, February 4, 2008

FastCGI: incomplete headers (0 bytes) received from server

Today I nearly spent my whole day in resolving a small problem which took hardly 30 seconds to resolve. The issue was quite simple. While upgrading one of the rails application on my local machine I suddenly started getting this error in my apache logs.
[Mon Feb 04 16:48:50 2008] [error] [client 127.0.0.1] FastCGI: comm with (dynamic) server "/home/chetan/www/myrailsproject/public/dispatch.fcgi" aborted: (first read) idle timeout (30 sec) [Mon Feb 04 16:48:50 2008] [error] [client 127.0.0.1] FastCGI: incomplete headers (0 bytes) received from server "/home/chetan/www/myrailsproject/public/dispatch.fcgi"
With this I put my seat belts on and started googling. There were many users who faced the similar problem while upgrading Rails. But each one was telling a different solution in his anecdote. I tried each of them but nothing worked for me. May be bad luck was not good today. I continued my hunt and kept looking for other solutions. Ultimately my prayers were accepted and I got the solution in one of the message boards. The problem was in the shebang line of dispatch.fcgi file. It was set to #!/usr/local/bin/ruby in the updated version, whereas in my machine ruby executable was located at /usr/bin/ruby. I fixed this and everything returned back to normal. I wish I had got this post in the very beginning so that my whole day would save. :)

Friday, January 11, 2008

Tata's 1-Lakh ($2550) car

Ending a long suspense and amidst a lot of media hype Tata motors finally unveiled its 1 Lakh ($2550) car `Nano` in 2008 Auto-Expo at Pragati Maidan, New Delhi. It was eagerly awaited for a long by the people. The launch of this car is supposed to bring another revolution in Indian auto market exactly the way it happened with the launch of Maruti 800 in 1980s. It can already be seen with Bajaj announcing its entry in small car segment in collaboration with Nissan and Renault by 2010. The prototype of this car has already been put on display in Auto-Expo. Similarly Suzuki Motors of Japan, a major share holder in Maruti-Udyog limited, has already tied up it's seat belt with development of a low cost 660cc engine for it's new car in reply to Tata's `Nano`. This car is also about to roll out somewhere in 2008.

As it was being expected the launch news immediately took the whole media like a fire with everyone from company personnels to media reporters to market analysts expressing their views about it. I noticed a mixed public reaction from various news channels about this car. People from lower to middle income groups are very excited as they can easily fulfill their long cherished dream of becoming a proud four-wheeler owner now. Along with being economical its smaller size demands lesser parking space in comparison to other smaller cars. Analysts also say that it will also impact the used car market by not only slashing their prices but also providing a new car option at the same price. On the other hand there is this another group who is worried with the repercussions from the over sale of this car on already deteriorating traffic and climatic conditions in cities. Delhi is at first place in this regard with the highest number of vehicles among all the metropolitan cities. The main target for this car would be two-wheeler aspirants who will now have the option to own a four-wheeler with slightly more investment.

Whatever people would say, but this much envisaged car of Mr. Ratan Tata is already in market now. It is powered by a 624cc 33bhp engine which claims to deliver a mileage of 20kmpl. It has an un-geared (continuous variable transmission) engine at the back powering the rear wheels. Despite its lower cost and small size company claims it to be completely secure from all security point of views. It is available in three variants, one basic and two deluxe. The showroom price of the basic version is Rs. 1-Lakh exclusive of VAT and road tax.

Thursday, January 10, 2008

Firefox loading blank pages

I had been facing this weird firefox problem for quite a few days in my linux box (Ubuntu 7.04 - the Feisty Fawn). After connecting to my ISP and browsing for few minutes suddenly all the URL requests were ending up in blank pages. Earlier I thought this was a problem with my ISP. But when I noticed that messenger and all the command-line tools (wget, lynx etc.) were working fine I understood that actual problem was something else. Considering the presence of some bug I first tried to upgrade the firefox (v2.0.08 to v2.0.0.11). Unfortunately this didn't solve the problem. I tried analyzing the http response headers using wget but couldn't gain much. Ultimately I had to resort to lynx with yahoo search as google was also dying with "400 Bad Request" message. After one or two attempts I got its solution in a forum. The problem was occurring with the pages responding with http 302 status. Some people also mentioned to experience the same problem with pages using script based redirection. Anyhow, the reason for this was attributed to some buggy firefox extension. With this knowledge it was easy to resolve the problem. Trying disabling each firefox extension one by one. I was too desperate to fix the issue ASAP, so I disabled all the extensions in one go. Voila! it worked and everything restored back to normal.

Tuesday, January 8, 2008

Singleton methods in Ruby

I am not a guru in any specific language. I work for a firm where technology keeps changing with projects. This time its again RoR. Before this I have worked on couple of RoR projects. With each project it seemed to me as if I was doing the same repetitive job, store and fetch data from database. So this time I decided to go a bit further and explore the language basics together with the new project.

After having a quick look at the rails core I got the first thing to start with.
class Foo
  class << self
    def bar()
      self.name
    end
  end
end

After googling around a bit I figured out that it's a way to create and bind a class to a specific instance or object. This binding class is called eigenclass, or more commonly a singleton class. Similarly, methods defined in a singleton class are called singleton methods. There is another alternative syntax for defining singleton methods.

irb(main):001:0> duck = Object.new
=> #
irb(main):002:0> 
irb(main):003:0* def duck.speak
irb(main):004:1>   'quack! quack!'
irb(main):005:1> end
=> nil
irb(main):006:0> duck.speak
=> "quack! quack!"
irb(main):007:0> 

Only the specific instance with singleton class has access to its singleton methods. The other instances from the same object's class don't share the added class and hence behave normally.

irb(main):001:0> duck = Object.new
=> #
irb(main):002:0> class << duck
irb(main):003:1>   def speak
irb(main):004:2>     'quack! quack!'
irb(main):005:2>   end
irb(main):006:1> end
=> nil
irb(main):007:0> duck.speak
=> "quack! quack!"
irb(main):008:0> 
irb(main):009:0* cat = Object.new
=> #
irb(main):010:0> cat.speak
NoMethodError: undefined method `speak' for #
This was all about the general idea. Lets move to some more depth beginning with a generic definition.
In Ruby, a singleton class is an instance specific anonymous virtual class that is created on the fly to hold the object specific behaviors (or methods). It is anonymous in the sense that it never appears in a list of objects returned from methods such as Module#ancestors or ObjectSpace::each_object, and virtual since it cannot be sub-classed or instantiated. It's only purpose is to provide a place to mount methods and instance variables that are uniquely associated with the specified object.

All the classes that Ruby creates automatically are marked as singleton (in class flags) internally. Also, like any other ruby class, a singleton class can also include modules.

irb(main):001:0> module BirdCharacteristics
irb(main):002:1> 
irb(main):003:1*   def can_fly?
irb(main):004:2>     true
irb(main):005:2>   end
irb(main):006:1> 
irb(main):007:1* end
=> nil
irb(main):008:0> duck = Object.new
=> #
irb(main):009:0> 
irb(main):010:0* class << duck
irb(main):011:1> 
irb(main):012:1*   include BirdCharacteristics
irb(main):013:1> 
irb(main):014:1*   def speak
irb(main):015:2>     'quack! quack!'
irb(main):016:2>   end
irb(main):017:1> end
=> nil
irb(main):018:0> duck.can_fly?
=> true
irb(main):019:0> duck.speak
=> "quack! quack!"
irb(main):020:0>
Now to grab the strategy behind the singleton classes lets first look at the structure of Ruby objects and classes. Each Ruby object consists of three main components:
  • A set of flags to store the meta-data about the object (like whether the object is frozen or tainted).
  • A hash to store instance variables.
  • A reference pointer (kclass) to object's class.
A class in Ruby is an instance of class Class. So it too contains all the three components described above together with
  • A pointer (super) to the parent or super class.
  • A list of methods.
 --------------------            -------           --------------
| object             |          | class |         | Parent class |
 --------------------            -------           --------------
| flags              |     ---> |  ...  |         |              |
| instance variables |    |     | super |-------> |     super    | ---> nil
| kclass             | ---      |   _   |         |              |
 --------------------            -------           --------------

Interestingly ruby objects itself don't store any methods. All the instance methods are stored in Class objects and shared by all the instances. When a method is invoked on an object ruby interpreter first searches the object's direct class using its kclass pointer. If it is found there then the method body is returned for the evaluation, next parent (super class) in the inheritance hierarchy is looked-up. This process continues until method is found, or no parent is available i.e. Root class (super = nil) is reached. In the latter case an exception is raised.

This was fine, but things get complex when it comes to invocation of class methods. Class methods like instance methods can't be stored in classes, or more specifically Class objects. If it is so, then they would be accessible from all the class instances using normal method calls. To resolve this ruby plays a small trick. Whenever a class method definition is encountered, it internally creates a new anonymous class, adds the class method to it, and binds it with the object manipulating the klass pointer. This new class is our singleton class. To retain the original behavior of object ruby manipulates the value of super pointer in singleton class to point the actual (instantiation) class object establishing an implicit inheritance.

 --------------------            -------
| object             |          | class |
 --------------------            -------
| flags              |     ---> |  ...  |
| instance variables |    |     | super |
| kclass             | ---      |   _   |
 --------------------            -------

                        Before class method definition
                        
 --------------------            ----------------------------           -------
| object             |          |         singleton class    |         | class |
 --------------------            ----------------------------|           -------
| flags              |     ---> |             ...            |         |  ..   |
| instance variables |    |     |            super           |-------> | super |
| kclass             | ---      | [.., new_class_method, ..] |         |   _   |
 --------------------            ----------------------------           -------

                        After class method definition

Now when a method invocation request is received ruby first checks the singleton class. If method is found then it is executed, else search is forwarded to the actual class using the super pointer in singleton class, followed by super class chain in case of failure.

All the methods defined for a singleton class are called singleton methods. The is another alternative method (other than the one described in the beginning) for defining singleton methods.

Saturday, January 5, 2008

Developing plugin with rails-engine 1.2 and Rails 1.2.x

After a much awaited opportunity to write a self contained plugin for rails application I ultimately got this chance with my new rails project where a new subsystem had to build for an already existing intranet application. The first thing I tried was to google around for some introductory articles or blog-posts about writing plugins using rails-engines. The ones I found were either outdated, or slightly confusing with vague description. So, I took this as a golden opportunity and decided to go ahead with this blog-post. At the time of writing of this blog v2.0 of engines plugin is available, revamped for using with Rails-2.0. I can't use it simply because the Rails application with which my plugin would ultimately integrate is live and running on v1.2.3.

Assuming that the required rails (1.2.x) application is there, we begin with the installation of engines plugin first.

1. Install engines plugin

railsroot$ ruby script/plugin install http://svn.rails-engines.org/plugins/engines
That's all with the installation part. With engines 1.2 no extra configuration is required in config/environment.rb. The only thing which is recommended but not required is to keep the loading order of engines plugin first before all the other plugins. This is possible starting with rails 1.2 using
config.plugins = ['engines', '*']
option in either config/environment.rb, or config/environments/*.

2. Create new plugin

railsroot$ ruby script/plugin generate myplugin
This will generate the following folder structure within root of rails application.
vendor/
  |
  plugins/
    |
    myplugin/
      |- lib/
      |    |- myplugin.rb
      |
      |- tasks/
      |    |- myplugin_tasks.rake
      |
      |- test/
      |    |- myplugin_test.rb
      |
      |- README
      |- Rakefile
      |- init.rb
      |- install.rb
      |- uninstall.rb

3. Create app, app/controllers, app/models, app/helpers, app/views, db, db/migrate, and assets folders within the root of newly created plugin.

railsroot$ mkdir vendor/plugins/myplugin/app
railsroot$ mkdir vendor/plugins/myplugin/app/controllers
railsroot$ mkdir vendor/plugins/myplugin/app/models
railsroot$ mkdir vendor/plugins/myplugin/app/helpers
railsroot$ mkdir vendor/plugins/myplugin/app/views
railsroot$ mkdir vendor/plugins/myplugin/db
railsroot$ mkdir vendor/plugins/myplugin/db/migrate
railsroot$ mkdir vendor/plugins/myplugin/assets
All the above created folders follow the folder structure of rails. `assets` folder corresponds to the pubic folder of the rails. It acts as a repository for all the plugin resources like images, stylesheets, javascripts etc. When rails starts then engines plugin replicates the content of this folder into public/plugin_assets/myplugin folder. All the resources in plugin's assets folder can be referred anywhere (generally views) using the extended Rails' helpers enhanced by the engines plugin to accept a :plugin option, indicating the plugin containing the desired resource.
# Include stylesheet from plugin
<%= stylesheet_link_tag 'mystyles', :plugin => 'myplugin', :media => 'screen' %>

# Include plugin javascript
<%= javascript_include_tag 'myfuncs', :plugin => 'myplugin' %>

# Incorporate plugin images
<%= image_tag 'logo.jpg', :plugin => 'myplugin' %>
<%= image_path 'header.jpg', :plugin => 'myplugin' %>

4. Migrations
Plugin migrations are required to generate tables for plugin models that can be shared with rest of the rails application. The creation of plugin migrations is similar to that of with rails. The only thing which needs to know is how to execute them. Unlike normal rails migrations, plugin migrations are not meant to be executed directly from within plugin. They are to be first migrated into the main migration stream using

railsroot$ ruby script/generate plugin_migration
in order to accurately reflect the state of appplication's database. Suppose according to the schema_info table in database the rails application is at version 35 and myplugin plugin contains a single migration 001_create_testplugin_table.rb in vendor/plugins/myplugin/db/migrate folder. Executing plugin_migration script
railsroot$ ruby script/generate plugin_migration
     exists  db/migrate
     create  db/migrate/036_create_testplugin_table_to_version_1.rb
will take rails applications to version 36 by adding a new migration 036_create_testplugin_table_to_version_1.rb to main migration stream i.e. migration sequence in railsroot/db/migrate folder. The content of this new migration would be something like this:
class CreateTestpluginTableToVersion1 < ActiveRecord::Migration
  def self.up
    Engines.plugins[:myplugin].migrate(1)
  end

  def self.down
    Engines.plugins[:myplugin].migrate(0)
   end
end
When the application is migrated up using rake db:migrate, then plugin will be migrated to its latest version (1 here). This can be verified by the new plugin tables in database. If at any time later it is required to rollback the application back to version 35 then it can be simple done by using
rake db:migrate VERSION=35
which will drop all the tables from myplugin migration (if specified in self.down method). 5. Generate all the controllers, models, views, and helpers for the plugin, exactly as we do in Rails, but this time only in context of the plugin.
vendors/
  |
  plugins/
    |
    myplugin/
      |
      app/
        |- controllers/ # Put all your plugin controllers here
        |- models/      # plugin models
        |- helpers/     # plugin helpers
        |- views/       # plugin views

6. Add routes for plugin

railsroot$ touch vendor/plugins/myplugin/routes.rb
Add all the required routes for the plugin.
connect '/login', :controller => 'myplugin/account', :action => 'login'

# add a named route
logout '/logout', :controller => 'myplugin/account', :action => 'logout'

# some restful stuff
resources :things do |t|
  t.resources :other_things
end
Don't prepend map (map.resource, or map.connect) with any of the routes. Also don't copy paste the application's routes.rb for plugin as the invocation of draw() method in it erases all the previous routes before adding the new ones. I had to struggle really hard to understand this minor stuff in lack of proper documentation. Add plugins' routes within routes of main application.
ApplicationController::Routing::Routes.draw do |map|

  map.connect '/app_stuff', :controller => 'application_thing' # etc...

  # This line includes the routes from the given plugin at this point, giving you
  # control over the priority of your application routes
  map.from_plugin :myplugin

  map.connect ':controller/:action/:id'
end
Be careful while doing this as the placement of this statement will directly affect the priority (Rails interpretation) of routes in the application.

Changing MAC address in Linux

Changing MAC addresses of network adapters on machines have become a mundane thing these days. For those using debian and ubuntu there are multiple ways to achieve the same.
ifconfig <interface> hw <hardware class> <mac address>
Example:
# /etc/init.d/networking stop
# ifconfig eth0 hw ether 00:00:00:A9:0A:3C
# /etc/init.d/networking start
The MAC address set via this way would be temporary and lost next time you reboot. The more better and persistent solution is to add the following line with interface settings in /etc/network/interfaces.
hwaddress <hardware class> <mac address>
Example:
iface eth0 inet static
address x.x.x.x
netmask 255.x.x.x
gateway x.x.x.x
hwaddress ether 00:00:00:A9:0A:3C
Don't forget to restart network using /etc/init.d/networking restart, or rebooting machine after this. There is another command-line tool available these days named macchanger, a GNU/Linux utility for viewing/manipulating the MAC address of network interfaces, which can also be used apart from the above mentioned two methods.
# /etc/init.d/networking stop
# macchanger -m 00:00:00:A9:0A:3C eth0
# /etc/init.d/networking start

Thursday, January 3, 2008

Things to know while developing plugins with rails-engine

There are massive radical changes with rails-engine 1.2.0. Earlier a new engine could be created using ruby script/generate engine enginenameThis has been changed now. With no more distinction between an engine and a plugin one can create a new engine (or simply a plug-in from version 1.2.0 onwards) using
ruby script/generate plugin pluginname
Do not copy and edit the plugin's routes.rb from config/routes.rb. The reason being draw method clears the existing routes before adding the new ones (Ruby on Rails 1.2.3: routing.rb). The following in plugins/pluginname/routes.rb might not work properly.
ActionController::Routing::Routes.draw do |map|

     # No map.connect here
     resource :resourcename
end
Instead only copy the desired routes like
resource :resourcename
I had to struggle for hours to understand and resolve the problems due to this minor issue.