Logo

Google goes BUZZing !!

6 months ago | Amit Kumar: RubyizednRailified

Google steps into the world of micro-blogging ....
Rest of the micro-blogging players hide out...

Wanna try -> here

See the video to help yourself...

Multipart form data post through ruby script

6 months ago | Amit Kumar: RubyizednRailified

Well its been long I blogged but better late than never... :)))
Been busy with projects, visit to India etc etc ... I can come up with a long list of excuses but none of them will be procrastinating ... hehehe

I forced my self out of hibernation to blog about a recent (strange ??) problem I faced.
In one of my projects, I came across a fairly common requirement to upload a file (multipart form-data post) through a ruby script. Pretty simple huhhh!

Unfortunately I was stumped to find that net/http library does not support it (still dont believe it!!). The documentation is very poor and it took me sometime to figure out net/http treats them all as string. CRAP !!!.

Some nice libraries eg: rest_client, httpclient, curb etc.. do a decent job in terms of posting the file, but they all mess with either creating incorrect boundaries for multi-part form or mess with content_length header of form-post

My requirement was to make http post call (multipart form data post) to Domino server. The domino app was very particular about content_length header, which is where I faced the biggest hurdle in using them.

Left with no choice, rolled up my sweet multipart form post.

Sharing with you all ruby-multipart-post.

How to use ==> here

Any feedback, most welcome ...

Enjoy !!!

A non-ruby post about marketing tips

about 1 year ago | Amit Kumar: RubyizednRailified

Goggling about some Ruby thing, I came across a nice article on Marketing Tips. I was forced to share these beautiful thoughts ....

http://www.webdesignerdepot.com/2009/07/9-marketing-tips-from-a-six-year-olds-lemonade-stand/

Installing Rails plugin from Github on Windows

about 1 year ago | Amit Kumar: RubyizednRailified

One more pain when coding on windows (as if I was born using Unix/Linux etc ;)))... but try installing a plugin -

ruby script/plugin install git://github.com/toamitkumar/extra_sanitize.git

and it will fail with an empty folder.

After googling found a way -> here which suggests using http instead of git protocol.

ruby script/plugin install http://github.com/toamitkumar/extra_sanitize.git

Well this also failed with an empty folder. After hours of struggling found adding a trailing forward slash to the url did the trick.

ruby script/plugin install http://github.com/toamitkumar/extra_sanitize.git/

It works now....

Extra Sanitize your models

about 1 year ago | Amit Kumar: RubyizednRailified

We have been using xss_sanitize, which is nicely bundled plugin. You drop it in your Rails application and rest the plugin takes care of protecting from XSS attacks. In our project, we found issues dealing with other special characters like -> microsoft single-double quotes, asterisk, percentage, tilda, angular brackets, question mark etc.

These characters cause extra pain to handle when they appear in urls. You have to encode/decode them. Rolled out a simple but effective plugin. It does nothing but puts an extra layer of sanitization on top of xss_terminate. Yes it is independent of xss_terminate and you can just use it.

Check the project page for usage.

Factory Girl - fixtures replacement for focussed and readable tests

about 1 year ago | Amit Kumar: RubyizednRailified

Why Factory Girl:

  1. Fixtures separates the data we are testing with actual behavior
  2. Makes tests brittle and you have to look at fixture files to understand the tests, which is certainly not the intent for the tests
  3. Its painful to have fixtures maintained for each model
  4. You have to keep switching between files to see what fixtures there are, always struggling with dependencies and conflicts
How to get started:
  1. gem install thoughtbot-factory_girl --source http://gems.github.com
  2. Add the following code to your test environment file ---> config.gem "thoughtbot-factory_girl", :lib => "factory_girl", :source => http://gems.github.com
  3. Add test/factories.rb if using UnitTesting framework or spec/factories.rb if using Rspec framework. It will be automatically loaded if defined at this location
  4. Ryan Bates has an excellent screencast @ http://railscasts.com/episodes/158-factories-not-fixtures
  5. Excellent documentation

GitHub - growing Social Network for Programmers

about 1 year ago | Amit Kumar: RubyizednRailified

GitHub is Public Open Source Git repository that's being called "Social Network" for programmers. Lets understand Git first.

Git is a distributed version control system co-developed by Linus Torvalds that has speed and efficiency. Git does away with the idea of a central repository. In Git every user has a complete copy of the repository data stored locally which makes accessibility easy and fast even when the n/w is disconnected. This seems radical to the concept of Subversion or other VCS (Version Control Systems) we have been using where the central repo has complete history (which makes it slow and inefficient). Git users have to push and fetch changes with each other. If any repository is lost due to system failure only the changes which were unique to that repository are lost. Once that system comes up it does push/fetch to update/get the changes. Git is extermely fast for all operations (except push and fetch), perform a diff, view file history, commit changes, merge braches, obtain any other revision of file, switch branches etc.

GitHub uses Git as a core technology while extending its basic ideas into the direction of social networking and publication. Everything you do with your source code on GitHub becomes a Web resource, complete with its own URL. Github is a pay service but it also offers free package which are suitable for many open source projects. GitHub really comes together for most users when you start talking about the social features. Every user and project has a profile. For ex: Amit Kumar (its me) is my profile page and Ruby on Rails is project profile page. The project profile page keeps track of progress and participation. Both users and projects profile page also have public activity feeds which display activity on public projects such as commits, comments, forks, etc. Users can follow specific developers or projects to keep tabs on the activity.

Getting started with github is very easy. The screencasts and podcasts are wonderful resources. Getting git and github on windows is a little timetaking but with msysgit latest version has made life easy. Github provides a beautiful of the master code and all the forks.


It lets you see everyone else who’s cloned a particular repo, and what changes they have made. The big benefit is that this prevents you from re-inventing the wheel when you see that someone is already working on the same feature you’re trying to submit. Instead of going and doing your own thing, you fork off of them and work with them. You might even fork off of a grandchild of the original project just because it has some feature that you need. It’s like the long tail of open source..you no longer have to wait for the original author to implement your obscure changes. Just find what you want out there and work with it. The reciprocal benefit of this, of course, is that the original author can actually watch your changes as you’re making them. Instead of some disjointed patches, he sees your commits as you add them to your own line and can follow your progress visually. At some point, if the author likes your work he can merge your branch back into his code. And GitHub will show this on the network, so everyone else who is following the project can benefit. They’ve made it easy to notify the author that you have some good changes as well, with the pull request.

Github is growing everyday. Statistics say after being launched in Feb' 08, in one year of being online it accumulated 46, 000 public repos.

Enjoy collaborating your project on github !!

Playing with Watir - File Upload/Download component

about 1 year ago | Amit Kumar: RubyizednRailified

In my last post I talked about WATIR integration with Rspec.

In our project, we had excel report download component. The challenge with Watir was to be able to download the excel file, save it and validate data against DB. Thanks to David Brown for his Excel Interface class library which is easy to implement. Next thing was to be able to save the file at any given location (always). None of the documented steps worked. The autoit dll supported by Watir was at the rescue. Au3Info.exe helps to identify IE control IDs. The following code snippet explains the rest:



After conquering file download, next was file upload. It was much easier coz Au3Info.exe was always their to figure IE control IDs. Using AutoIt documentation simplified it further.



WATIR rocks !!

Read only models in ActiveRecord

about 1 year ago | Amit Kumar: RubyizednRailified

I was working in one of my project, where we were required to connect to 2 databases.

  1. First we had access to do CRUD
  2. Second we were only supposed to READ
For the second DB we wanted to raise exception from Rails, if somebody by accident tried to create/edit. ActiveRecord has this attribute as part of all models already called @readonly. There are definitely few challenges. Here is what I did:

The sweet model:


If somebody tries to add a record:


If someone tries destroy


What if someone uses delete


Rest in peace !!

Playing with Watir

about 1 year ago | Amit Kumar: RubyizednRailified

Past few days I have been playing with using Watir in my current project. I bet it has been fun. Watir gives this awesome power for automated testing. Many would argue why not Selenium for that matter. There were few challenges using Selenium:










FeatureWatir/WatijSelenium
Frames and popup supportEasyHas problems
API for database connectivityEasyDoesnt have API support
Multi language (non-ascii character)supportEasyNo
RecorderYesOnly for FF
Integration with RspecEasy to create a test suite. See example below
Cross domain supportYesNo
Ajaxified responsesYesDifficult


One of the fun part was attaching your browser instance to your IRB. The examples here is self sufficient explanation. If not, then watir-console is theie for rescue.

Not to forget the Excel Interface Class, which we used to download an excel report (as part of our project) and match the values against DB records.

The rspec task to run the tests as a suite and also lets you connect to environment specific database:

desc "Run all watir tests "
namespace :spec do
Spec::Rake::SpecTask.new(:watir) do |t|
ENV["WATIR_ENV"] = ENV['env'] ? "#{ENV['env']}" : "development"
t.spec_files = FileList['test/integration/watir/*_spec.rb']
t.spec_opts = ["-fh > public/watir_results.html"]
end
end

From the command prompt you could run:

>> rake spec:watir (runs and connects against development database)
>> rake spec:watir env=qa (runs and connects against qa database)

Lately, a lot of progress has been made on Watir Recorder

Unobtrusive Javascript -> a new paradigm in Javascript Programming Language

about 1 year ago | Amit Kumar: RubyizednRailified

Current buzzword in the world of Javascript is unobtrusiveness. People who use it frequently make their website accessible, or they want to develop their project using Progressive Enhancement. Lets start by understading each term to make sense by being unobtrusive.

Accessibility in javascript means that as many people as possible will have access to the content or functionality of the page even if the Javascript implementation in their browsing device is lacking or nonexistent.

Progressive Enhacement, is a methodology for building web pages using graceful degradation model - the intent of making advanced content fail without breaking the rest of the website for less sophisticated browsers. In simple terms being unobtrusive is to segregate behavior from structure and presentation in a HTML document.



Following unobtrusiveness pattern the code stays clean, easier to read, and more maintainable.

You people might be thinking what sense or non-sense I am talking about. Lets try and understand it with the simplest example. Lets say we have to create an anchor tag, onclick of which a javascript will be fired to add an item. We are used to writing code like this:

  • <a href="javascript:addItem();" mce_href="javascript:addItem();">Hit Me!</a> ----> WORST
If javascript is disabled nothing will happen.
  • <a href="#" onclick="addItem();">Hit Me!</a> ---> JUST as bad
Using inline event handlers is not inherently inaccessible but the href attribute doesn’t lead anywhere so the end result is the same as in the first example.
  • <a href="/add_item" onclick="addItem();">Hit Me!</a> --> BETTER
Now we have a real target for the anchor, so the link is already fully accessible assuming that the add_item URL provides the same functionality as the addItem Javascript function does. However, the code is still a mixture of behavior (javascript code) and structure (the HTML).

  • <a href="/add_item" id="item_link">Hit Me!</a> + $(‘item_link’).click(function() { addItem();}); (when using Prototype) $('#item_link').click(function() {addItem()}); (when using jQuery) --> BEST

Now the HTML file takes care of the structure (just as it should), and the behavioral logic is separated into a separate Javascript file. This is both accessible and unobtrusive.

Welcome to the world of jQuery one of the most unobtrusive style of Javascript library. One would argue even Prototype is the same. But having used both I can figure out the difference. To list a few:
  • jQuery has no IE memory leaks
  • jQuery supports almost all browser I can call name of (many of the features of prototpe does not work in IE eg: inline-editing)
  • Method chaining - all native jQuery method support chaining i.e. they return self. eg: $("div.fadeMeAndThenRemove").fadeOut().addClass("removed");

jQuery is being widely used -> Google, mozilla.org, wordpress.org, DELL, digg, NBC, drupal etc... are few names who have moved to using jQuery.

Enjoy being unobtrusive !!

Lightweight Javascript Table Sorter using Prototype

about 1 year ago | Amit Kumar: RubyizednRailified

The Javascript tablesorter is built on top of Prototype library. The library gives the dynamic feature of row formatting, maintain the sort order of the table on dynamic addition/deletion of a row, default sort order when the page loads, keep one or more columns unsortable, make multiple tables sortable on the same page etc.


Usage:

* The table should have an id attribute
* It should have thead > tr > th as headers.
* It should have tbody > tr > td as body.
* thead > tr > th[class="integer"] will make the column int sort
* thead > tr > th[class="date"] will make the column date sort
* thead > tr > th[class="float"] will make the column float sort
* thead > tr > th[class=""] will make the column string sort
* thead > tr > th[class="nosort"] will make the column unsortable
* thead > tr > th[class="sort-asc"] will make the column default sort on page load
* sorterId = TableSortObserver.sortableTables[table_id];
sorterId.resort(sorterId.sortIndex, sorterId.sortOrder);
This will resort the table after dynamic addition/deletion of a row. It will retain the last sort column.

Initialize:

* TableSortObserver.bindEventsToTableRow(table_id)

The TableSortObserver retains all the sortable tables registered on the page. The sorter has been tesetd on IE 5/6, FF 2/3, Chrome, Safari.

Update: Source code on github

Flex + Rails = Flexible Rails -> Rich Internet Applications

about 1 year ago | Amit Kumar: RubyizednRailified

The wave started in 2007 when Simeon Bateman presented Building Rich Internet Applications with Flex and Ruby on Rails @ Rails Euro Conf. Both Rails and Flex are two great tools to quickly develop nice looking and compelling applications.

For those who don't know Rails -> Type Ruby on Rails on google and the result will overwhelm you :)

Quick introduction to Flex:

* Flex is cross platform development framework for creating RIAs, Desktop applications
* It is component based. Coding is done in MXML (Macromedia XML), ActionScript 3 (Object Oriented, Strongly type)
* Flex Builder and SDK are used for design and code view
* Flex 3 framework is Open Source
* Compiles in swf file which runs in Flash Player ref in HTML page
* Support RESTful API

A typical communication that happens between Rails and Flex component:



Worldwide ubiquity of Adobe Flash Player 9 Sept-08 -> 89.4%.

Recently published book by Peter Armstrong (Manning Publication co.), explains the seamless integration through RESTful APIs. Another one is talks about why Flex is better than using Javascript and CSS.

In our project we were looking for a component to bulk upload documents (always painful). Flex gave the power to bulk upload documents and integration with Rails was pretty straightforward. browse() and upload() method of FileReference class does the whole magic.

Wanna Test the Flex Component ?
For geeks who like to test every piece of code they write Flex 3 provides FlexUnit, a unit testing framework for Flex and ActionScript 3.0 which mimics JUnit and comes with graphical test runner.

The beautiful flex component:



Wanna try the power of Rails combined with the flexibility of Flex ??

Code to come shortly

URLEncrypt rolled out as plugin on Github

about 1 year ago | Amit Kumar: RubyizednRailified

In my last post I talked about encrypting RESTful urls when we have to expose primary key in the URL. The plugin is generic and exposes handy methods.

Repository:
http://github.com/toamitkumar/url_encrypt/tree/master

Installation:
.scirpt/plugin install git://github.com/toamitkumar/url_encrypt.git

Usage:

Add the following line to your environment.rb file

UrlEncrypt.encryptors("abcdefghijklmnop", "mnbkjhkhkhkhkhkjhkjh")
#so that KEY and IV for Cipher encryption are different

OR

UrlEncrypt.encryptors("abcdefghijklmnop")
# so that KEY and IV for Cipher encryption are same

OR

NOTHING

Inside your model add the line:

class Book < ActiveRecord::Base
  column :id, :integer
column :title, :string

encrypted :with => :title
end

You have handy methods:
Book.find_by_encrypted_title('encrypted string')

Book.find_by_encrypted_title('encrypted string',
:conditions => ["any other condition can go here"])

Next step: To roll out the plugin as JRuby.

Undefined method "updated?"

about 1 year ago | Amit Kumar: RubyizednRailified

I was juggling around to find out the cause. I kept on getting error:

NoMethodError (undefined method `updated?' for #): /vendor/rails/activerecord/lib/active_record/attribute_methods.rb:251:in `method_missing' /vendor/rails/activerecord/lib/active_record/associations.rb:907:in `belongs_to_before_save_for_person' /vendor/rails/activesupport/lib/active_support/callbacks.rb:173:in `send' /vendor/rails/activesupport/lib/active_support/callbacks.rb:173:in `evaluate_method' /vendor/rails/activesupport/lib/active_support/callbacks.rb:161:in `call' /vendor/rails/activesupport/lib/active_support/callbacks.rb:93:in `run' /vendor/rails/activesupport/lib/active_support/callbacks.rb:92:in `each' /vendor/rails/activesupport/lib/active_support/callbacks.rb:92:in `send' /vendor/rails/activesupport/lib/active_support/callbacks.rb:92:in `run' /vendor/rails/activesupport/lib/active_support/callbacks.rb:272:in `run_callbacks' /vendor/rails/activerecord/lib/active_record/callbacks.rb:298:in `callback' /vendor/rails/activerecord/lib/active_record/callbacks.rb:206:in `create_or_update' /vendor/rails/activerecord/lib/active_record/base.rb:2200:in `save_without_validation' /vendor/rails/activerecord/lib/active_record/validations.rb:901:in `save_without_dirty' /vendor/rails/activerecord/lib/active_record/dirty.rb:75:in `save_without_transactions'

I have 2 models Person and Rate with

class Person
  has_many :rates
end

class Rate
  belongs_to :person
end

On create/update of person or rate, I kept on getting the error. After deep digging I found the cause of the issue.

In my Rate model, I was creating a @person object. The association (belongs_to, has_many etc..) calls before_save callback for associated model. Since I created a new @person object in my Rate class, it was calling 'updated?' for new object and hence NoMethodError.

I renamed the @person object and resolved the issue.

Hope this helps.

Encrypting/Decrypting primary key appearing in the URL

over 2 years ago | Amit Kumar: RubyizednRailified

I paid a small cost for being RESTful.

As RESTful suggests, the GET request will always have the primary key in the URL like: http://somesite.com/somecontroller/123/edit

In the app we have role based access and only admins have access to edit. We made sure that the application is protected and only admins can update an existing record. The so called Security had a different perspective. They were not willing to expose the id(=123). The solution was to encrypt the id.

I came across a good blog here.

Following the same concept:

  1. I added a EncryptDecryptHelper module inside my lib directory. The module has 2 methods.
  2. encrypt -> used OpenSSl Cipher RC4 digest and Base64 encoding of the string for an already defined KEY and IV
  3. decrypt -> used the same KEY and IV to decode the string
  4. Included the module inside my model and over-ride to_param to encrypt the primary key.
  5. Added a before filter method on the application controller to decrypt the primary key.Made sure we are passing objects instead of id while creating links eg:-
  • Do:
<%= link_to 'city', :controller=>'cities',:action=>'show',:id => @city %>

Instead of:

<%= link_to 'city', :controller=>'cities',:action=>'show',:id => @city.id %>

The security team is happy now.

Remove rake tasks

over 2 years ago | Amit Kumar: RubyizednRailified

Ever tried over-riding rake task ?

I tried to over-ride and I found that the default always gets called after your implementaion.

Here is what I tried doing:

namespace :db do
  namespace :test do
    task :prepare do |t|
        puts "Skipping Preparing database for Oracle"
    end
  end
end

But the default db:test:prepare was always getting called.

To solve the probelm:

Inside your Rakefile just below you require the rake modules put the following code.

Rake::TaskManager.class_eval do
  def remove_task(task_name)
    @tasks.delete(task_name.to_s)
  end
end

def remove_task(task_name)
  Rake.application.remove_task(task_name)
end
remove_task 'db:test:prepare'

namespace :db do
  namespace :test do
    task :prepare do |t|
      puts "Skipping Preparing database for Oracle"
    end
  end
end

Voila, the italicized code to override the default rake tasks worked.

Hope this helps !!