Skip to main content


Showing posts from 2011

Deals You Can't Miss

1 Year Subscription

Prevent rails from pluralizing table names

In the Database world, it is the convention for the table names to be singular. Rails irks the pure DB-folks by pluralizing table names. In my previous project, the DBA was terribly upset with the pluralized table names that was created because of Rails and was hell bent on singularization of the table names. I won't blame him for that. In fact, I support it. But know what Rails is an awesome framework, you can ensure that the table names are not pluralized with a single configuration line in your project's environment.rb file.

Rails 3 and its Sandbox

Rails console has always been a friend in need for the Rails developer. More often, we get to the console to try out some coded snippets to verify and validate our assumptions, either while writing the test cases or during the coded implementation. In this process it is very likely that we end up modifying the state of the underlying database. This inturn can cause some headaches or frustration. Nonetheless you soil the database with junk data. If you are fine with it, then read no further - this post is not for you. If however you are wondering for a way to SANDBOX your play environment from soiling the database, then read on. Run your console with the command as below: $ rails c --sandbox  That is all you need to do to maintain the sanity of your undedrlying database. So what does this sandboxing do? It keeps journaling all the activities that you do on the database and will undo it all upon exit so that the database goes back to the state previous to sandboxing.  There are

Miniature Code Retreat

I was so excited with the idea of Code Retreat invented by Corey Haines , that I pushed for conducting a miniature version it (with just two sessions of pair-programming) at Dev Camp Chennai, 2011 . My Goal of conducting a Mini Code Retreat First and foremost, my agenda was to market the Global Code Retreat that is to happen on the December 3rd of 2011.  There are very few corporates that follow TDD, pairing and "refactoring". If folks who can participate in the session, get a good hang of and appreciations for it all, then they would well become agents to market the experience of good practices. Its been a long while since I facilitated. I personally wanted to see where I stand in facilitation and see what I derive out of this session as a facilitator. What I did to achieve my goals Dev Camp was a good crowd puller and I wanted to use that occassion to ensure that I give people the taste of what really Code Retreat is all about. Soon after my welcome address, I

Agile Tour 2011, India

Agile Tour 2011, India @ Chennai on 12-November-2011 I had the opportunity to give two extempo lightening talks to the people at this conference. The topics were, "The attitude that an individual and team has to carry when the CI build breaks" and "Planning is important but plans are not" . I felt compelled to share my experience and thoughts on those topics,  because I observed that the delegates were discussing about it more and wanted more clarity. How my talks were received? Oh I guess, it was well received as many could understand and appreciate it prompting them to talk and ask more questions about Agile post my talks. I doubly enjoyed it, because there were both developers and management folks equally interested to learn more and more by way of discussing things in their mind with me. Secondly, Preethi Madhu, ThoughtWorks India, Head of Consulting, was happy to provide a very positive feedback to me. Thanks Preethi :) May I request your feedback

Vim for Rails Developer

Every person gives feedback based on his understanding of things which is dependant on his level of skills at that point in time. For the reader of this post, who is interested in knowing my background to better evaluate my feedback, I have elaborated in brief my history of experience in the RoR world of application development. After spending about 10 months in my first JRuby on Rails-2,  two-developer all-chaotic first non-pairing project, where I was using RubyMine as IDE for all practical development purposes, I resolved to try out a new IDE in my next Rails gig. Folks at ThoughtWorks are in the habit of experimenting and trying out different IDEs. And hey, I was no exception ;) - prior to RubyMine , I tried Vim and Aptana RadRails , but for whatever reason I loved RubyMine, perhaps because I was too familiar with this one by virtue of my experience of using IntelliJ in Java projects. As decided I did choose a new IDE when I moved on to my second RoR3 gig and it was Vim. Why

Leveraging Subject in RSpec - A rough cut!

Do you use subject in RSpec? This blog post intends to help you get better with RSpec's subject. The better way to learn things is by way of an example; even better if we see a bad example and see how we can progressively improve it. The better way to write the above test is as below: Further refactoring the above code snippet, it can be compacted to below, although I hate to do this. I prefer to tests/specs being an utter no-brainer to read quickly and get the idea: Finally the ideal way of testing the above scenario and the like would be to employ RSpec's subject as below: If after reading all this you were to wish it be more leaner, then you should consider shoulda. Will blog about it's marriage with RSpec sooner ;) Until then see how snappier the above code becomes with the use of shoulda matchers. Hooray!!!

SQL Logging in Rails Console IRB

In order to quickly find the SQL queries that are fired against the DB, while you are playing on the Rails Console, all you need to do is set ActiveRecord's Logger to STDOUT as below: >>ActiveRecord::Base.logger =

Custom finders and SQL Injections

Everyone writes bad code. The most awful and potentially very dangerous ones that cannot just cannot sit in the commit-able code are the badly written raw SQL queries or even your API code that can give leeway to SQL Injections or SQLi .

[ERROR] couchapp error: You aren't in a couchapp.

Every CouchApp must have a .couchapprc file in the application directory. This file is a JSON object which contains configuration parameters that the command-line app uses to build and push your CouchApp. The couchapp generate and couchapp init commands create a default version of this file for you. If you don't have a .couchapprc file, couchapp will display the dreaded couchapp error: You aren't in a couchapp message.

Can't find first MyFreakingActiveRecordModel

Can't find first MyFreakingActiveRecordModel.... Do you get this weird sounding error on running your spec for the model? A re-look at the exception should give you some cues. Yeah, it only implies that you don't have a test record for that model in your test environment DB. All you need to do is add a test record to the test DB. If you are using FactoryGirl, and RSpec, the code snippet below shows the way it can be done elegantly. Lesson: Shoulda requires a record in the DB, well atleast in this case :P

Rails 3 - Filtering Sensitive Parameters From Being Logged

If you are wondering, "How on earth do I ensure that sensitive parameters are not logged anywhere by the Rails 3 application?". Well, its a cinch as far as Rails goes. All you need to do is add all your sensitive parameters to filter_parameters list in config/application.rb file. A sample Rails3 config file having this setup will look as below (MyRails3App is the name of my rails application):

Untrack a file in Git

git rm --cached <file>  The good thing about this command is that it will merely remove the file from the history tracking index. The local copy of the file will not be removed. The story in detail...learning by experience [practice]$ mkdir myproject [practice]$ cd myproject/ [myproject]$ git init Initialized empty Git repository in /home/karthik/MyRubyProjects/practice/myproject/.git/ [myproject(master)]$ git st # On branch master # # Initial commit # nothing to commit (create/copy files and use "git add" to track) [myproject(master)]$ touch abc.txt [myproject(master)]$ git st # On branch master # # Initial commit # # Untracked files: # (use "git add ..." to include in what will be committed) # # abc.txt nothing added to commit but untracked files present (use "git add" to track) Situation 1: If you were to untrack a newly created file that you added to staging for commit. [myproject(master)]$ gi

Kill process listening/bound to specific port

Step 1: Identify the process     For this you can use either of the command below: lsof -w -n -i tcp:<port_number> where, -w implies suppression of warning messages -n option inhibits the conversion of network numbers to host names for network files. Inhibiting conversion may make lsof run faster. It is also useful when host name lookup is not working properly. -i[i] option selects the listing of files any of whose Internet address matches the address specified in i. If no address is specified, this option selects the listing of all Internet and x.25 (HP-UX) network files.       If -i4 or -i6 is specified with no following address, only files of the indicated IP version, IPv4 or IPv6, are displayed. (An IPv6 specification may be used only if the dialects supports IPv6, as indicated by "[46]" and "IPv[46]" in lsof's -h or -? output.) Sequentially specifying -i4, followed by -i6 is the same as specifying -i, and vice-versa. Specifying -i4, or -i6

When you see Gem error like - "'': uninitialized constant Gem::SilentUI (NameError)"

I just created a new Rails 3 project called dashboard and tried having bundler install all the required basic gems for this project using the command - bundle install. Damn!, I got the error that is the title for this blog post. Below is the snap shot of the command and the error: karthik@cloud:~/MyRubyProjects/beach_projects/dashboard$ bundle install /home/karthik/.rvm/gems/ ruby-1.9.2-p0@rails3/gems/bundler-1.0.7/lib/bundler/ui.rb:56:in '<class:UI>': uninitialized constant Gem::SilentUI (NameError) from /home/karthik/.rvm/gems/ruby-1.9.2-p0@rails3/gems/bundler-1.0.7/lib/bundler/ui.rb:2:in `<module:Bundler>' from /home/karthik/.rvm/gems/ruby-1.9.2-p0@rails3/gems/bundler-1.0.7/lib/bundler/ui.rb:1:in `<top (required)>' from /home/karthik/.rvm/gems/ruby-1.9.2-p0@rails3/gems/bundler-1.0.7/lib/bundler/cli.rb:16:in `initialize' from /home/karthik/.rvm/gems/ruby-1.9.2-p0@rails3/gems/bundler-1.0.7/lib/bundler/vendor/thor.rb:246:in `new' fro

How to find the method definition - one that is invoked at runtime?

During the QnA session after my talk at RubyConf India 2011, one avid Ruby enthusiast asked me a question, "How to find the method definition - one that is invoked at runtime?". I confessed that in all my experience (for the last eight and odd months) with Ruby, I have been doing the grep-ing for the method name and then figure out which method definition would be the last to over-ride every other ones declared earlier. No sooner did I finish answering, boooooooooom came a greatly handy tip from a very respectable and renowned geeky person in the crowd - Ola Bini . He adviced to use Ruby's "method" method to figure out the source of the method that was invoked at runtime. What an easier and neater approach! Hearty thanks to both the folks - one who questioned and the other who answered. This blog post is my attempt to elaborate more on the tip that Ola Bini had adviced. Back home after the conference, I googled on these lines and found the following re

Ruby Conf India 2011

I happened to be one of the speakers in this international conference that was held at Bangalore. What pleasure and privilege! The subject of my talk was Deciphering the Ruby Object Model , aimed to help fellow ruby enthusiasts level up their understanding and appreciation of Ruby as a programming language. The talk was well received by many a folks who had attended my session. I wish to thank every one who had personally come over to me for sharing their feedback with me. You can download the presentation from any of the below mentioned locations: Slideshare  (PPT version only) RubyConfIndia  (Both PPT and PDF versions available here)  Once the conference videos are published, I'll be glad to add its link here ;) Okie, it is now published, so please find it below: Deciphering The Ruby Object Model from Innovation & Technology Trust on Vimeo . For all the positive feedback I had received, I intend to very soon publish a couple of blog posts detailing on specif

... the gem has no specification file. Run 'rake gems:refresh_specs' to fix this.

Did you happen to vendorized gem and get a warning message like, "... the gem has no specification file. Run 'rake gems:refresh_specs' to fix this." ? Afterr looking at the warning message did you try running the suggested rake command - rake gems:refresh_specs - to no avail? What next? How the heck do I get rid of this warning message? Well, in times when gems for some reason doesn't vendorize the requisite specification file for that vendorized gem. You may have to run the following command in the respective gem's vendorized directory: gem specification gem_name_without_version_number > .specification Here is an example of my case wherein, I vendorized the factory girl post my installing it in my gemset and tried running the server. I got a warning message as below: config.gem: Unpacked gem factory_girl-1.3.3 in vendor/gems has no specification file. Run 'rake gems:refresh_specs' to fix this. kartz@desktop:~/MyRubyProjects/my_project$

How to disable gnome-ssh-askpass?

Today we had setup Git repo with access to it through corporate's LDAP authentication. From the client machines we can access it using the .netrc (where the machine, login and password are configured). However, for some wierd reason, upon trying to pull/push commits from/to the Git repository, the bash shell tries to open the gnome-ssh-askpass dialogue and it fails. I wanted to prevent the bash shell from attempting to launch the dialogue box. To do this, all I had to do is run the following command in the terminal: $ unset SSH_ASKPASS To prevent it in future, you can add the above line in your .bashrc or .bash_profile. Wish you trouble-free working!

No DHCPOFFERS received. No working leases in persistent database - sleeping.

I was getting this weird error " No DHCPOFFERS received. No working leases in persistent database - sleeping. ", when trying to connect to internet via WIFI in Ubuntu. After enough googling to no avail, and by sheer serendipity I solved this. This worked for me; may be it helps you too. Argh, I missed the point. So here is what you can try if you are stil having this issue. Step 1: Go to, System -> Preferences -> Network Connections Step 2: Select Wireless tab Step 3: Click "Edit" the wifi connection profile you have created Step 4: There are two connection modes - Ad hoc and Infrastructure. Choose the "Infrastructure" mode Step 5: Save and try connecting again. You are done...!

GVim, Vim, Vi key-board short-cuts

Switch between tabs      Ctrl+PageUp,   Ctrl+PageDown     Ctrl + Shift + UpArrow ,  Ctrl + Shift + DownArrow Move to Nth tab in gvim      gt, gT      Note: The advantage with using gt, gT keys are that you can move to [N]th tab. For eg., if you want to go to 3rd tab type 3gt Open a file in new tab from NERDTree while still remaining in NERDTree      T will open the selected file in new tab, without changing focus from NERDTree      t will open the selected file in new tab, and changes focus to that tab Recursively Open all child nodes          Activate the NERDTree and navigate to the directory whose all child nodes must open.     Now press O (capital) to expanded list of child nodes    Recursively Close all child nodes     Activate the NERDTree and navigate to the directory whose all child nodes must close.     Now press X (capital) to collapsed list of child nodes Close all tabs at once with a single command, when I have multiple tab

Consolidating DB migration in Rails

In my current project we used to maintain a good number of rails migration scripts until, one guest developer stepped into the team for a short while and shared his knowledge on consolidating Rails DB migrations which I intend to blog about in this post. So what is consolidating DB migrations all about? So if you have the DB migrations say, 1_aaa.rb, 2_bbb.rb and 3_ccc.rb that has gone into your production release 1.00, post your successful release (or a day or two after that), you can consolidate the scripts to something, say 3_consolidated_migrations.rb, wherein this new script essentially borrows the id (here it's 3) from the last run migration in production release and the contents being the same as schema.rb So what are the implications of this? Well you need to keep in mind of the following: Without this approach being adopted, we can just about run the DB migrations on DB dump irrespective of its snapshot date. To put it other way, adopting this practice implies tha

tar command (with compress option)

Reading through the Unix's man or manual for a command description may be a little pain but with repeated practice you get used to it. In this blog I mix the manual's content and add my own example which might be of frequent use in general. SYNOPSIS tar [-] A --catenate --concatenate |            c --create |            d --diff --compare |               --delete |            r --append |            t --list |              --test-label |            u --update |            x --extract               --get [options] [pathname ...] DESCRIPTION Tar stores and extracts files from a tape or disk archive. The first argument to tar should be a function; either one of the letters Acdrtux, or one of the long function names. Some options take a parameter; with the single-letter form these must be given as separate arguments. With the long form, they may be given by appending = value to the option. FUNCTION LETTERS -A, --catenate, --concatena

No more cron jobs. Schedule jobs through rufus-scheduler in rails.

In the project that I'm working currently, I was asked to look out for ways to replace the scheduling jobs through crontab in favour of some scheduler that can control/schedule run the tasks at regular interval as long as the application is up and running. Thanks to my comrade in Dev-Ops team (Ranjib Dey) who  directing my attention to rufus-scheduler. rufus-scheduler - Things can't be simpler! Let us see how simple it is in action with a sample code  First step to usage is install the gem; so, find below the command for the same. You run it from the root of your application folder and I assume that you use rvm (if not, prefix the command with - sudo ) > gem install rufus-scheduler Now, when the rails application gets kick-started, it reads all .rb files under config/initializers directory as part of its initialization process. This step in rails start-up, is what we'll take advantage of. So, let us create a new file, say my_tasks_scheduler.rb , in config/initial

Externalizing ALL application specific configurations to a file outside of Rails ROOT

It has been quite a while since I wanted to externalize all application specific configurations to a file outside of Rails ROOT, so that when my application is deployed in production, it picks up the configurations from a file in some specific location outside of Rails environment. The sysadmin makes changes to this file as is required and he alone knows or is eligible to know all these configuration details and certainly not the development team. The application that I'm having in my mind is an internal rails application that gets deployed in an internal hosting environment instead of hosting it in a external environment like Heroku, etc. Follow through the self-explanatory code snippets to get an understanding of how I achieve it in simple way. For the noobs, the quick explanation would be that the code snippet in environment.rb file reads the YAML file from system to copy all key value pairs to Rails' ENV hash. This ENV hash is available everywhere while/on/after appl

Run SQL in Unix Shell

While reading the book -  Agile Web Development with Rails, Third Edition  - I have come across a section where the authors show how to run a SQL against a sqlite3 database. Want to know where in that book you can find it? Go purchase the book and find it yourself :P Now back to my business of curiosity - I wanted to know how do I do this in every other databases that I have used so for. This blog post is a record of that endeavor. This should be very handy mainly for the Rails developers. Unix, SQL and SQlite3 linux_prompt$ sqlite3 db_file_name.sqlite3 "SELECT * FROM my_db_table" linux_prompt$ sqlite3 db/development.sqlite3 "SELECT count(*) from schema_migrations" linux_prompt$  sqlite3 db/development.sqlite3 <<EOF > SELECT * FROM users; --where 'users' is a table in my development.sqlite3 DB   > SELECT * FROM schema_migrations;  --where 'schema_migrations' is a table in my development.sqlite3 DB >EOF Unix, SQL and M