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.

Wednesday, December 26, 2007

Trip to Pachmarhi from Bedaghat

Pachmari is a small and charming hill-station located in a valley of Satpura ranges in the central state of India, Madhya Pradesh. It is also known from the name of "Queen of Satpuda". Our journey to this place started from Bedaghat, a small but exquisite and another must-see tourist spot in Madhya Pradesh renowned for its picturesque marble rocks standing either side of river Narmada.

There is no direct conveyance from Bedaghat to Pachmari. The only reasonable way is to reach Jabalpur station first, the main transit point located at some 18 KM from Bedaghat, and then travel a 3 hrs. (around 200 Kms.) train journey to Pipariya. Pipariya is the main stoppage point for almost all the conveyance from Bhopal to Pachmari. One can get shared jeeps and interstate buses plying between Bhopal and Pachmari from here. Shared jeep costs 40 bucks per person whereas state owned public transport buses charge 15 bucks per passenger. Its worth mentioning that apart from these two sources there is no other way to reach Pachmari from Pipariya.

It was Saturday and the only train to Pipariya in morning was Pawan Express at 0930 hours. We had a quick breakfast of samosas and tea in a small shop at Bedaghat. We had like 40 minutes to catch the train with the only available conveyance at that moment i.e. public tempos. It was impossible to reach the station on time if tempo driver, like usual, would halt and take passengers from in-between. So we haggled with him and hired the full tempo for 110 bucks which otherwise costs 15 bucks per person.

Despite the 35 minutes continuous drive we couldn't make to reach the Jabalpur station on time. The train was scheduled to depart at 0930 hours whereas we reached around 0935 hours. There was a short queue at the ticket counter. We were in hurry so I stood in the queue and my colleague went to inquire about the train. Fortunately train was late by an hour and a half due to some unknown reasons. This gave us a huge relaxation and we breathed a sigh of relief. We had enough time and we utilized it with our brunch and newspaper in railway refreshment room. Despite the re-scheduled arrival time of 1120 hours the train actually arrived the station at around 1135 hours, some 15 minutes late. It waited there for some 10 minutes before re-commencing its onward journey.

The journey was appearing to be smooth when suddenly an unexpected incident occured blaring the horn of our woes. We were traveling on general ticket as it was a short journey and getting instantenous reservation was impossible. Despite the full occupancy we managed to steal two seats for us in sleeper class. It would have hardly spent an hour when TTE came. We were taken aback when he told us that we had a general ticket which didn't allow us to travel in sleeper class. We persuaded him that it was not a deliberate act but he didn't accept it and fined us 600 bucks. We had no other option but to pay. This filled the rest of our journey with slight dismay.

The train dropped us Pipariya at 0245 hours. The first thing we did there was to seek conveyance to Pachmari. Luckily an interstate bus was standing at the bus stop just outside the station. But when we reached there we saw that it was already occupied. On inquiring we came to know that the next bus was at 1530 hours. Weather was moderately hot and it was difficult waiting for next bus with heavy baggages. As a result we decided to try our next and only option, shared jeeps. There were plenty of them at the same spot. Some of them were partially occupied and waiting for few more passengers to depart. But whoever we asked he replied the same, "We are already booked." After many unsuccessful attempts we left the hope for jeep and decided to better wait for the next bus. In between we had enough time for lunch and we left for some restaurant in vicinity.

coming soon more ...