Wednesday, December 31

Qucik Fix: ActiveRecord Migrations reset_column_information

Few days back I had created few migrations that would rename existing table and again create a table with old name.
  1. user should be renamed as "old_users" 
  2. create a new table "user"
  3. restore the data with different column names in the "user"

  def self.up
    rename_table :users, :old_users
    create_table :users do |t|
      t.column :created_at, :datetime
    end  

    Temp.find(:all).each do |user|
      new_user = User.new(:id=> user.id, :created_at => user.created_at)
      new_user.save!
    end
  end

Don't worry about the Temp, Temp is a class through which I am accessing the old_users table.  Precisely,

class Temp <>
  set_table_name "old_users"
end

This worked pretty well in my local environment and when I deployed in staging, it crashed.  The error was that, it was trying to insert data into table with prvious structure/columns.  Which means, the new structure hasn't taken effective.

The quick fix seems to be reset_column_information.  Before pushing/creating fresh data in the table, I need to reset the column information of the tables.  So including the following line:
      User.reset_column_information
right before creating new users solved the problem.

By the way "WISH YOU HAPPY AND PROSPEROUS NEW YEAR"

Quick Fix: YAML syntax & Fixtures issue

Today I got a mail from one of my juniors who was struck with some strange problem.  
While he started playing with built in unit tests in one of his rails project, he got an error

Errno::ENOENT: No such file or directory - ramesh

  I was bit confused with this error and asked him to send me a screen shot of the error so that I can understand it better.  And here he sent the following snapshot,

Well when I got this it was very clear that the problem was with fixtures.  So I peeked into his fixtures, which is like this:


having looked into the fixture,  it was pretty clear that this is about right syntax.  And this was the quick fix which worked out:


Quickly revising back about YAML & Syntax while defining hierarchical elements would give you clear view of this quick fix.

  Anyways, it was the mistake in the indentation while defining the YAML :)

Tuesday, December 30

Usability Tip: Ajax loading/busy indicator

What is Ajax?
In a nutshell, "With Ajax,web applications can retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page".

  Now that these requests are happening at the background, user should be aware that the application is trying hard to retrieve the data.  But, How do we do that?

This is where we can use Ajax loading/busy indicator.  We show some text/image saying that we are working/loading... until the request is completed.  This would increase the usability and end user will be happy enough.  
  I am going to show it's implementation in RoR based web applications.  

Module ActionView::Helpers::PrototypeHelper, takes care of Ajax implementation through prototype library.





as you see the rails form tag helper comes out with interesting usability options. Above we just implemented, :loading & :complete options where-in it would show/hide particular div ("loading"). And what's in that div?




well it's done.  
Few samples...




Do I need a designer? 
hmm... we don't need designer for every thing. Especially this usability can be entirely handled by developer.  

How do I create an image? I don't have prior experience! 
Not needed just follow 3 simple steps 
2. select Indicator type, colors. 
3. Generate & Download It  

I don't know RoR, how can I do it in PHP/Python/Java/JavaScript? 
This needs prototype, JavaScript library that provides DOM manipulation. The same is achieved like this:



use the above snippet.

Thursday, December 18

Tweak: updating ruby gems

Recently was helping my friend to setup a twitter based application on server.  And gems needed to be updated as ruby gem "twitter" needs rubygems of  >=1.2.0
  And as usual passed the update query and after a few minutes there is an interesting message saying "nothing to update". 
  There seems to be a minor tweak to achieve this.  A two step tweak which needs another gem installed and then update.
  1. gem install rubygems-update
  2. update_rubygems
and that does the trick ;)

Monday, December 8

Range Class in Ruby

"Range" is an interval with starting and ending values. In ruby ranges can be created either by "literals" or directly through the "Range::new". And of the literals, x..y & x...y. The main difference of the two mentioned literals, inclusion/exclusion of end values in the range.
x..y: includes the end values

(1..5).each do n
puts n, ' '
end


(1...5).each do n
puts n, ' '
end
In the first literal case, values 1, 2, 3, 4, 5 would be printed. Whereas, in the second litereral case 1, 2, 3, 4 only will be printed.

Interestingly methods end/alias would still give the end value of the range. In such case, end_excluded? is apt choice to distinguish.

Wednesday, November 12

Integration Testing: xml_http_request

I was referring to Agile Web Development with Rails book to implement the Integration testing. And as per the book it

xml_http_request "/store/add_to_cart" , :id => ruby_book.id

and strangely I was getting syntax error. Seems the book did miss out another parameter which would define the method type. Referring to online documentation, made things clear.

xml_http_request(request_method, path, parameters = nil, headers = nil)

Performs an XMLHttpRequest request with the given parameters, mirroring a request from the Prototype library.

The request_method is :get, :post, :put, :delete or :head; the parameters are nil, a hash, or a url-encoded or multipart string; the headers are a hash. Keys are automatically upcased and prefixed with ‘HTTP_’ if not already.

Saturday, November 8

Ajax even @ home - I am serious

It's been over two years I heard about this buzz word "AJAX". In fact I came to know about this through one of resumes that I interviewed for php programmers. And once I picked up Ruby on Rails framework, it became pretty common in daily work. Well to cut short and justify title of this post "Ajax even @ home - I am serious". Can't believe? See down ...



Have a nice weekend :)

Thursday, October 16

SnappyFingers - a new way of learning through FAQ's

The way we study, understand, evaluate a particular topic, subject, product is been changing. Ever since the internet boom had made it's mark and search engines like Google, Yahoo... listing down many relevant topics from Wikipedia, webopedia ... useful sites this was seen more prominent.
Let me put it this way, just search through relevant topic and keep filtering the appropriate website(s). I feel many of us would like to understand a topic with basic and frequently asked questions What? Why? Where? How? Which? Who?
Matching to above criteria and thinking process, I found a new product in the market "relevant answers for your frequent questions" - SnappyFingers. It's a smart explorer that would fetch across the relevant answers for your questions. SnappyFingers made the process of finding answers pretty easier.

Thursday, September 4

My Experiments with Google Chrome - 3

This article was shared by Shakti. This is nothing to do with the extensive feature list of chrome, or bugs, or fixes... but on the privacy policy.
Google's Chrome Terms of Service take out a royalty-free license for Google of any content submitted by users over the internet...
Read it from source... http://tapthehive.s483.sureserver.com/chrome.html

Wednesday, September 3

My experiments with Google Chrome -2

As mentioned in my previous post, the import firefox bookmarks is picking up some random profile.  The reason behind this is while importing the chrome could not access the settings of current profile and hence picking up the random profile setting.

Can we have importing based on the profile?

My experiments with Google Chrome -1

I just installed the chrome and started experimenting it. Based on my earlier posts on Add-ons, extensions, profile usage, browser features... one can understand how much I use/love the Firefox browser. As soon as installed the chrome, I started looking for the same. But then I realised it might take some time before I could notice the features that I am fond of.

profile usage:
I extensively make use of this profile feature. I create multiple profiles, based on my work.
  • To create new firefox extension.
  • To test the extensions.
  • For office work.
  • ...
  • ...
Importing bookmarks:
Though I prefer using stumble to bookmark my favorite pages, for quick reference I store some on Firefox bookmark tool bar. When I tried with chrome, it had imported bookmarks randomly from one of the firefox profiles.

Addon's:
I feel the usability of browser increases with these add-on's, extensions.

Google Chrome

Thanks to my friend Aditya, for sharing Google Chrome the browser from Google.
I am always eager about the products that comes out of Google. I am under impression that whatever Google comes out with will have more usability, simplicity, to the point, light weight... and I can go on listing them.
From Google's official blog entry, I went through the story behind building the Google Chrome. It was quite impressive and it shows the approach is really good.
keep watching and experimenting...

Wednesday, August 27

RoR course: RSS Maker/Parser

Download the pdf
View on Scribd

I would like to share the details of how Ruby supports to generate and read the RSS. Before going into details, let us look into few basics of what we are going to deal with.

There will be very few and hardly few people in this web world who does not know about the RSS/Feeds. To keep things simple and elegant:

Note: An RSS document is often referred as “feed” or “web feed” or “channel”.

What is RSS?

  • Really Simple Syndication.
  • It is a easy way to share defined content and news/titles/posts from www
  • RSS is written in XML

Why use RSS?

RSS can be updated automatically; this enables users to track/monitor their favorite sites, news channels, websites… without even going/visiting the sites. Since it is simple, light and fast-loading this can be used even in PDA’s, mobiles thus ensuring the accessibility even simpler.

Who should use RSS?

RSS is ideal to be used if the source is dynamic. In the sense that would change rapidly for say new sites, micro/web blogs… RSS is not meant for static pages, website that doesn’t have updates frequently.

Well the next obvious question would be How do I read them?

With so many websites/blogs/calendars… everybody generating the RSS, the reading/grabbing job is taken care by “RSS/feed reader” or “aggregator”. These aggregators can be either desktop based or web based. The user needs to subscribe his favorite site feeds by submitting the RSS link provided by the site to these aggregators and they would send the user the subscribed updates as and when they occur.

Having answered the few basic “W’s”, it would make perfect sense for us to plunge into RSS implementation of the same in Ruby on Rails.

Ruby excellently supports the RSS implementations. RSS (v0.9, v1.0, v2.0), maker and parser. Moving ahead here I will be showing few examples how do we parse/generate the RSS feeds in Rails application.

Note: An RSS document is often referred as “feed” or “web feed” or “channel”.

Parser:

Parser identifies the feed Url provided and reads the document and we can publish the feed with our own display options. So all that we need is a simple feed url. Let us say we need to publish the feed content of particular site on our blog/site.

Since there are multiple versions of the RSS available based on the version we need to include/require those libraries while parsing the feed.

  1. A controller that would handle all the feed related actions, includes/refers the required libraries.
  2. An action/method that would use the rss/parser library to read the feed.
  3. Extract the necessary elements/content.
  4. Pass on the elements/content to the views.

require 'open-uri'

require 'rss/0.9'

require 'rss/1.0'

require 'rss/2.0'

require 'rss/parser'

require "rexml/document"

class RssFeedController <>

#This action is used to get the rss feed of the blog mentioned

def parse_feed

url = 'feed url'

rss = RSS::Parser.parse(open(url){|fd|fd.read})

item_rss=rss.items.collect{|item|item.title}

item_link=rss.items.collect{|item|item.link}

@p=item_rss.length

@postfeed=item_rss

@postlink=item_link

@link="url of the link"

return @postfeed,@postlink,@p,@link

end

end

The view part will be a list of articles/content displayed looping over the length of feed.

<%@postlength.times do|i|%>

<li>

<a class="define style" target="_blank" href="<%=@postlink[i]%>">

<%=@postfeed[i]%>

a>

li>

<%end%>

Thus we are done with parsing or reading the existing feed or RSS document.

The view part will be a list of articles/content displayed looping over the length of feed.

Maker:

Maker creates/generates the feed/RSS document of a site/blog. Since there are multiple versions of the RSS available based on the version we need to include/require those libraries while making the feed.

  1. A controller that would handle all the feed related actions, includes/refers the required libraries.
  2. An action/method that would use the rss/maker library to read the feed.
  3. Extract the necessary elements/content.
  4. Pass on the elements/content to the views (RHTML/RXML).

def generate_feed

version = "2.0"

content = RSS::Maker.make(version) do |m|

m.channel.title = "Title of the post/entry"

m.channel.link = "http://www.linktopost.com"

m.channel.description = "Describe the post"

i = m.items.new_item

i.title = "Ruby to generate RSS feeds"

i.link = "http://www.linktopost.com"

i.description = "Describe the post"

i.date = Time.now

end

end

As you find the above two actions were created for RSS 2.0, hence we have the elements as title, link, description, date… which are as pert RSS 2.0. Based on the version we are referring/using they would change accordingly.

This is a static content based on which we created the feed, to create a dynamic feed say for the posts, articles should iterate over them and pass the info accordingly.


In nutshell, Ruby provides the RSS support with

RSS::Maker.make

RSS::Parser.parse

There are umpteen number of rails plug ins were created and available for rails community that were built on the above mentioned core ruby classes.

Feed Fetcher

Feed Tools

Resource Feeder

Atom Feed helper

This document is prepared as part of Ruby on Rails course that I am writing in blog TechSavvy.

Have something to discuss/suggest/enhance: Reach me tosumanthkrishna (gmail)

References:

http://en.wikipedia.org/wiki/RSS

http://www.w3schools.com/default.asp

http://www.rubyrss.com/

Download the pdf
View on Scribd

Wednesday, July 30

Career Steps: How to tell the world what I am ?

I could not wait for long time to write this post, continuing what I had started in my previous post Career Steps: Tell what "you" are to the world?
many might be already thinking of implementing/doing few of the mentioned points. But how you do it makes you really different, isn't it!
  • Register into relevant/interesting groups/forums & be a watchdog there.
  • Actively take part in the technical talks/sessions.
  • Try to excel in particular concept and be ready to show your capability. (When u r ready, opportunities sure to come!)
  • Keep shouting/discussing at community groups/forums.
  • Be attentive and ready to extend your hands to the people with doubts.
  • Show you professionalism.
  • Start socializing.
  • Maintain your personal pages/blogs/websites.

These are just few of the ways that I can immediately think of and I welcome all to suggest more ways if they have any...

Well here comes the action items:
Rails Groups & Forums: (For ruby enthusiasts)
http://www.ruby-forum.com/
http://railsforum.com/
http://groups.google.com/group/ruby-on-rails-programming-with-passion
http://groups.google.com/group/rubyonrails-talk
http://groups.google.com/group/rubyonrails
http://www.orkut.com/Community.aspx?cmm=46323518
http://www.orkut.com/Community.aspx?cmm=1198032
http://www.orkut.com/Community.aspx?cmm=188
http://groups.google.com/group/bangalorerug


Professional Network:
http://workingwithrails.com/ (for ror professional)
http://www.linkedin.com
http://www.ecademy.com

Social Networks
http://www.facebook.com
http://www.orkut.com

Personal Page:
http://www.blogger.com
http://www.wordpress.com
http://pages.google.com/
http://myspace.com

Online Knowledge Base:
http://www.scribd.com
http://www.slideshare.net
http://www.slide.com

Bookmarking sites:
www.stumbleupon.com
www.digg.com
www.delicious.com
http://del.icio.us/

Career Steps: Tell what "you" are to the world

I was wondering when thousands of people are obtaining similar (professional) degrees, and developing more or less same skill sets,
  • How one I be picked as best from the rest ?
  • How can I show that I am different from the rest?
  • How can I make it to the top cream?
  • How do I know where am I standing in the skill/domain...?
  • How do I show my expertise?
  • ...
  • ...
  • ...
Well this how we should start thinking whenever we are about to apply for any job or looking to grow high in the career path.

Sunday, July 27

Websites -> Weblogs -> Micro Blogging -> ? what next?

I was just recollecting how the internet had changed the people, business, culture, thought process and the list can go on and on... But I am just amazed the ways and means of showcasing, marketing one about their skillset, work capabilites and portrait themselves to this wide world.
Websites:
where you pile up lots and loads of content in form of pages and users/visitors can go through leisurely.

Weblogs (Blogs) :
Later moved to weblogs, popularly known as blogs, for more interactive, updated content.

Micro-blogging:
We are now even ahead of blogs with micro-blogging concept. Users can post limited text about what they are doing?

What caught my attention is how dynamically we are becoming and more dynamically we are able to develop the software tools that can keep up our dynamism, agility, communication, information gathering. So also the market coping up with new trends, millions of websites, later came the revolution through blogs (wordpress, typepad, blogger...) and now the micro-blogging popularised by twitter, jaiku. This micro-blogging became so famous that it influenced well established web applications/products to embed this feature into their own systems.

I observed them in the following places:
LinkedIn, Orkut, Facebook, Digg...

So what next after this micro-blogging?
Are we heading to "nano"???

Thursday, July 17

Scaling of Twitter - What's the truth ?

Twitter, there might be very few web browsers who does not know about twitter. For the benefit of those few, Twitter is a micro-blogging service that allows users to send updates.
Twitter used to go down due to the page views load. There is been lot of discussions, questions regarding the scalability of the Twitter. And I too faced many people asking the scalability, capability of the Ruby on Rails (technology with which twitter was built) in building the web applications.

Twitter started as a side project and blew up fast, going from 0 to millions of page views within a few terrifying months. Early design decisions that worked well in the small melted under the crush of new users chirping tweets to all their friends. Web darling Ruby on Rails was fingered early for the scaling problems, but Blaine Cook, Twitter's lead architect, held Ruby blameless:


For us, it’s really about scaling horizontally - to that end, Rails and Ruby haven’t been stumbling blocks, compared to any other language or framework. The performance boosts associated with a “faster” language would give us a 10-20% improvement, but thanks to architectural changes that Ruby and Rails happily accommodated, Twitter is 10000% faster than it was in January.
Hope that clears some air around twitter discussions. Interestingly, there are quite a number of applications that are build around twitter gaining popularity.
twittervision, summize (twitter search) to name few.
Twitter was made very handy with lots useful tools/extensions on every platform that you can think of. From desktop to iphone users, the gadgets are available here.
I too tweet here!
Few slides that comes handy when you want to speak/read, how the scaling of twitter is getting improved.
View/Download From Slideshare.
Scaling-twitter by Blaine
Scaling-twitter @ railsconf-2007

Friday, July 11

Internet Technology Bubble :)

This video show how smart people utilized the Internet Technology bubble. And the interesting thing is we still have lots of scope. As the pioneers set the stage and now it is very simple for me and you to reach heights soooooooooooooon. Just sharpen your brains and we can be there.
Well I towards this elite group.




There are many bests in this video!
One that caught my immediate attention is Revenue/Property Comparison between Facebook and Ford.
Grab wat u liked here and happy weekend :)

Friday, July 4

Firefox Extensions - Set as Startup Page(s)


A quick fix for this extension. The latest version will have the options set in context menu(i.e, on mouse right click) and under Tools menu options. The button from the status bar is removed now.
Thanks to Prashant for his feedback and I will implement the suggestions in future releases.



Download Extension
We browse umpteen number of sites/pages across the internet everyday. If you like them and you want to keep the selection as startup pages for your browser (FF), you have to change the options manually.

I thought (as most users feel!) it was not convenient and so I ventured to make it as simple extension. Well if you are like me then, "Set as StartUp Pages" is one such simple and profound extension which would let you set the startup pages with a simple button click from your status bar.

How it works?

1. Install the extension.

2. Restart the browser instance.

3. You will find a button "Set Homepage(s)" in statusbar.

Correction:
Button from status bar removed.
Options are visible in Tools menu and context menubar.


4. Browse across pages in as many tabs you want.

5. Click the button to set them as startup pages.

6. An alert message would confirm the above step.

7. Clicking on 'Home' icon, you can see the implementation.


Set As Startup Page(s) - Download

For next release:

1. Option to set the pages just on mouse right click.

2. Help page with instructions.

3. To improvise the alert/confirmation message.


Note: I would like to get your feedback before I submit to Mozilla Add-ons repository.

Set As Startup Page(s) - Download

Wednesday, June 18

Career Steps: Product based company OR Service based company?

Briefly introduction to make it understandable to one and all:
Product:
an item that ideally satisfies a market's want or need
Service: provision of assistance to customers or clients, products or projects
The product or service is nothing new and it exists in every domain/space across the industry. Let me take up IT as I am into it. Well I started my career with a product based company. From then on I was fortunate to be associated with innovative products, budding products wherever I go.
While I was having a chat with one of my room mates, who worked with few java based projects there arose a little interesting topic, Product based company OR Service based company.
I just raised the same question with Linkedin community to provide their views as follows:

In IT which is good choice to shape a good career is it in Product based company or Service based company? Please give the pro's of each and also con's (if any!)

Following is the response from Rajesh Tibrewala, in which he covered the answers/views of the rest of people who attempted to answer the question.

It varies from person to a person. What i can share with you is how life in one differs from another:

1. Product Based Companies

You spend a lot more time with the same technologies, same code base, and often the same set of features.
You can never know your customer too well - remember, a product is ultimately an attemp to fit the same shoe to feet of all shapes and sizes (but the alternative is the software industry is - people would need to walk barefeet because turnkey projects are too expensive)
If you work on a successful product for a long period of time, the sense of achievement can be tremendous
Seeing a lot of happy customers is thrilling indeed
There are often comparitively long periods of lull - when the product strategy team is trying to figure out the future roadmap, and the latest release is already out
Often you will end up working on a codebase that noone owns - becuase the product is very old, and none of the original code authors are around. Also, the technology the product is based on could be nearing its death


2. Projects

Often developed from scratch - so you start with a clean slate
You get to know your customer very closely
Fast movement across domains, and often technologies
Direct appreciation by the customer
Often more time pressure compared to product cos

Well I selected this as best suit answer (in my view). Please read here for the rest of answers.


My LinkedIn Profile : http://www.linkedin.com/in/sumanthkrishna

Tuesday, June 17

Career Steps: Go by the work and not just by the "BRAND" !

To be frank nobody told me about this, but over the time I understood it. Well the credit goes to my managers and superiors who took special care in teaching me part of industry.

The reason behind the post is, I was at an Engineering college in outskirts of Hyderabad to take a session on Ruby, as part of Open Source talks. Thanks to SWECHA, for giving me the opportunity. Before I started the session I had few questions to the group of 200 odd students so that I can deliver what they are looking for? (Hitting them straight, without wasting my time!).
Interestingly not many of them are aware of any scripting languages, until SWECHA organised series of sessions/talks.
Well during the ruby talk, I did not bug them with usual slides but just directly walked through examples (that kept them awake and attentive through out the session!).
During the Q&A, the usual questions were fired up:
  1. What is the future for Ruby?
  2. Can Ruby be used for Desktop and Mobile applications?
  3. Java vs Ruby?
  4. Python vs Ruby?
  5. Who are all implementing/working on Ruby?
Let me pick up the 5th question, as rest of questions were answered by many people on various occasions. The actual question they raised was :
Does the company X, Y, Z implementing it?
And then list of few big IT brands started flowing out of them, well I just wondered whether they are looking for the exciting work they will be assigned or just by the "BRAND". Here comes the role of placement officers of the institutes very well to bridge the gap. Occasionally, many groups with industry people visit these colleges to give an exposure and understanding of the industry, current trends, demanding technology/tools...
But what about the colleges that do not get these groups/industry people do not visit?
This is where everyone need play pro-actively in deciding their career based on their interests, knowledge, skills. Students/Freshers should start interacting more with industry people, start gathering/attending to technical/industry forums, discussions and talks.
This kind of socializing will make them understand the reality and they can be prepared for the same and this would help the industry to get skilled people or right attitude people.

As far as I know, Twincling is the one such group with lots of momentum among the student groups, communities, industry that is doing it's role of spreading the awareness. Twincling members are ready to travel length and breadth of Andhra Pradesh (for time being) and conduct workshops for free. Contact the group for more details.

Wednesday, May 7

Extra Money OR Extra Skill !!!

There is slight personal experience attached to this post. Though I though it will fit on my personal blog, still the skill/technlogy is involved it would equally fit even here.
It's been three years (short of few days) in this IT industry. It's been great learning and at every stage and reminds me there is still more to learn.
There was a great temptation in the initial days to look out for extra money options. It's the general feeling that every individual carried on with. It was the time when Blogging culture was spreading very rampant in India and across the world, I got few opportunities to work with Wordpress Blog Engine.
Somehow, the way of the customization, deployment and taking it to live was very very simple(at least I felt) at the same time decent money. From then on I started working towards improvising/gaining more and more knowledge on Blogs. I started marketing myself as Blogger/Blog Expert.
  • Marketing a Business/Company/Individual
  • Making blog as revenue generator.
  • Improvising the Blog/Website traffic.
  • SEO (Search Engine Optimization)
  • Google AdSense and Adwords.
  • RSS Feeds.
  • Blog Widgets.
  • Rich User Interface.
  • Blog making it more user centric.
  • ....
  • ...
The interesting point was slowly went deep into these things and "Extra Money!!!" was forgotten long back and "Extra Skill !!!" was the driving force.
Extra Money:
  • You start looking out more options only when you feel/evaluated/decide that this going to be paid later.
  • One may find difficult to survive as the competition grows.
  • Transition to other technologies/expertise is difficult.
Extra Skill :
  • With gaining knowledge in the back of mind, you explore more and more soon you will discover that you have an edge over others.
  • Survival is not the issue as your interest was to gain more knowledge/expertise.
  • This is not a transition, but just another skill set.
I can keep listing out more and more.
Coming on to my experience, though I ventured out as an Extra money (though not so successful) option this was really turned out to be an Extra Skill (which I really feel added some flavor to my skill set).
There are more such things which can not be comprised into single post. But I thought to reveal more as series of posts :)

Wednesday, April 9

Build your own OpenSearch/Sherlock engine

It's been long since I blogged anything other than Ruby on Rails. I am trying my best to make RoR tutorials as simple as possible. Just little bit deviation from RoR but still on to Web based topics - "Browsers".









I thought of writing a post on creating/building an opensearch engine for your own site, but I just documented for better understanding and made it availble to download/view online.

The document covers the two approaches to create a search client. The code snippet contains the code with sphred as the example site.








View on Scribd:
Download :


Feedback/Suggestions welcome :-)

Thursday, April 3

ActiveRecord - CRUD operations - 2

We learn t how to create rows in the database. Moving next in CRUD, it is Reading data from db tables. Reading data involves/requires set of constraints/conditions. Something like, details of specific user, product pricing range, sorting order, matching criteria... and the list goes on. To go ahead with these operations ActiveRecord provides the following handy methods, parameter symbols to you:

find
find_by_xyz
find_by_sql

:first :all :conditions :include :order :limit :select :joins :offset :readonly :lock
etc...

Getting into details, previously we created few rows about user into users table. Now we use this find to read/retrieve the data. Little about "find", it is counterpart for "select * from users" in SQL. The syntax is very plain and simple to pick up.
Say, now I want to read/retrieve the data of all users.

User.find(:all)
so the find method connects to users table (through User class of model) and through parameter "all" it fetches info of all the users a simple array. If we use parameter :first, then only first record would be fetched.
User.find(:first)
say now I want to introduce some constraints. :conditions is the parameter to be used.
Like, I want user with a specific name
User.find(:first,
:conditions => "name='sumanth'" )

but in case the name to be matched comes dynamically through params, then there would be slight change in the above syntax. Like this,
User.find(:first,
:conditions => "name=?,params[:name] ")

or

User.find(:first,
:conditions => "name= '#{
params[:name] }'")


if you want more than one parameter to be checked/matched in the conditions then we can separate each with 'and'.

User.find(:first,
:conditions => ["name=? and email=?",params[:name] ,params[:email]])
thus we can play around with more options/parameter that "find" accommodates. Don't forget to separate each options with "," as I had used it after :first and before :conditions options.

Wednesday, April 2

ActiveRecord - CRUD operations -1

Having seen how do we handle the relationships across db tables through rails now let us dig little deeper on how to perform CRUD operations.
Create
Read
Update
Delete
Well Rails ActiveRecord does help you out with lots of keywords and many more convenient, easily understandable, meaningful commands. In nut shell, you can carryout all these sql queries without using sql syntax at all...

Inserting data - We generally use SQL Insert statements to insert/create new rows of data and Rails offers a simple way of creating new rows in tables. One of doing it is by using "new" or by "create" method.
The syntax looks very simple, as below:

Based on previous posts we can coolly observe/interpret the above code like this:
  1. As per ActiveRecord pattern in rails, this says that User is the model connecting to users table in database.
  2. All the columns (eg:name here...) of the "users" table go in do ... end loop, 'u' is the iterator.
  3. Once you set the values of each column then end with save (u.save).
Why to save?
Because, new method would only creates an object and so to store into db we need to explicitly say it to save.
Is there any alternative one?
In many instances, people create objects, define the data and they tend to forget saving the data. Active Record offers another method, create, which would instantiates the model object as well as stores it into the database.


Using both new, create methods we can either insert multiple rows of data or even the form data can be passed as parameters.

Wednesday, March 19

ActiveRecord - Connecting to DB and tables

I thought compiling of all my previous posts and documenting would be of great help to all users including off line. I compiled all the posts where I discussed on
Connecting to databases
Pluralization convention
Relationships between tables
...
Download here

View on Scribd

this would help all to keep in touch before we go deeper on to more Active Record.
more fun awaiting :-)


Thursday, March 13

Firefox Profile Manager

I am fond of using the one of the key feature of Firefox browser i.e., Profile Manager. For developers especially, it means not to mess up our work.
I prefer to use each different profile for the different extensions/add ons that I am working on for Firefox browser and not to mess up these with my default profile which I mail use for browsing and mailing purposes.
For the benefit of first timers, profiles can be created (in Windows) from the run command window
I run teh command
  • firefox.exe -P
  • firefox.exe -profilemanager

With Minefield (Firefox 3.0*) around we need to start our development/testing even on Minefield apart from regular FF2.0*. Now the same old commands of creating profiles firefox would not work...
Since the minefield is intalled, and being latest the above commands would result in creating profiles in the Minefield but not into the Firefox. There is another command which many might have forgotten:

  • "C:\Program Files\Mozilla Firefox\firefox.exe" -profilemanager
  • "C:\Program Files\Minefield\firefox.exe" -profilemanager

Thanks to my friend Aruna, whose query had made me dig into Profile Manager of Mozillazine Knowledge base and resulted in writing this post.

ActiveRecord association has_many :through

We had seen how a has_and_belongs_to_many works with a join table. But apart from carrying the foreign keys the join table has nothing much to do over there. So to have more features added and retaining the goal of having many-to-many relationships we will discuss now another rails offering "has_many, :through".

The above snippet shows a simple example from Josh Susser's blog.
The scenario shows that there are two tables "books" and "contributors" and the a join table "contributions". This is entirely different from habtm, where we had the join table with combination of tables.
And syntactically, we say to each of tables (books, contributors) that they are related to each other through "contributions".
So the join table would have a simple belongs_to and the individual tables will be related with has_many:'table_name' and keyword :through=>'name_of_join_table'

That is with the ActiveRecord relationships. Just to recap
has_and_belongs_to_many
has_many, has_one, belongs_to

We will be slowly moving into other part of rails packages, ActionPack soon.

Sunday, March 9

ROR Workshop -1

Ruby on Rails workshop went on well. As stated in my previous post, I introduced the Ruby and Rails. Spent bit time around how the web applications work in general and the features that rails equipped with to address the each and every requirement.
Though I am not getting into more details in this post, soon I will be writing/discussing more about them. I thought I would thank one and all in making this workshop pretty informative and very good overall.
Members of Twincling Community
Saifi
Namita
Sumith

My Friends
Rajesh Batta
Hareesh Kumar

My Juniors
Anas
Hafeez
Haritha
Lokesh
Rasheed
Sravanthi

and the great audience. At the end of the day, I felt very very good when few of the attendees asked details about next session.

In fact, I would like to cover few other topics like, Testing in Rails, Exceptional Handling, Migrations & Generators and Plugin integrations ... feel free to comment :-)

Friday, March 7

RoR Workshop @ Hyderabad - Twincling

I am planning for a workshop on Ruby on Rails introductory level. The agenda of the workshop is

  • to introduce the Ruby on Rails
  • MVC Architecture
  • ActiveRecord
  • ActionController
  • ActionView
  • ActionMailer
  • Pagination
  • Ajax
  • Rails demo with project
For more details about the venue and organisation details, visit Twincling.
More about the workshop will be updated through the posts, keep watching :-)

Saturday, March 1

has_and_belongs_to_many : habtm in Rails

has_and_belongs_to_many, simply "habtm" of rails would address/handle the many to many relationships of the tables.

Let us take this scenario where we have two tables, "products" belong to "categories" and "categories" belongs to "products" in more than one ways. That is each product belongs to many categories and each category contains many products. In each of the model, category and product the relation would be shown using habtm (has_and_belongs_to_many).






Closely observing the above example, we can see that the products table and categories table contains habtm relation. There is an intermediate table "categories_products", which would carry the primary key of each table.

At the database level this is achieved using an intermediate join table. The convention followed here is the name of the join table is the concatenation of the two target table names but in alphabetical order. In our example, we joined the table categories to the table products, so Active Record will look for a join table named categories_products.

Note:

  1. The join table carry the foreign keys of each table.
  2. There will be no model for this intermediate table (categories_products)

Well that precisely explains how we implement many to many relationships in Rails. That is not all there is one more way of expressing the relationship between tables, "has_through" which we will touchbase later.

Tuesday, February 26

Ruby on Rails relevance to Startups - @ BarCamp

The barcamp5 hosted by Google Engineering Hyderabad :)
Many bloggers had already spoken their part about the proceedings through live blogging.
In brief, there was bit chaos on arranging things, running the talks/session parallely, and finally it was more like session with less user participation (devitation from what usual BarCamp famous for!!!)

Sumanth Krishna @ Ruby on Rails Conferences/Communities


I wanted to present on my favorite Ruby on Rails and since BarCamp is the place where lot of young minds, entrepreneurs... assemble. So I related it (RoR) to Startups and on "Ruby on Rails relevance to Startup's". I started the session post lunch around 3PM. I did present my views on very well about the startups and when the slides related to Ruby on Rails started, I just carried away more in explaining the details of RoR.


Slides: "RoR relevance to Startups" @ Google sponsored BarCamp5 :)
Scribd
SlidShare


Please feel free to enhance/comment on the presentation.
I am planning for a Workshop on Ruby on Rails with support of Twincling society :-)

Wednesday, February 13

Relationships between tables - How ActiveRecord handles?

Keywords:
  • has_one,
  • belongs_to,
  • has_many,
  • has_and_belongs_to_many
  • polyphormic
  • one-to-one
  • one-to-many
  • many-to-many
It's known that any web application will contain bunch of tables and they are dependent on each other. With normalization as the key, we avoid redundancy and have more relationships with tables using keys. In database terms, the following are the relations allowed/known between tables -> one-to-one, one-to-many, many-to-many. Let us digg more, how ActiveRecord handles these.
ActiveRecord supports the above mentioned relations and in fact, comes with set of key words which are easy to use, understand and pretty clean.
Let me take few snapshots from David's book:
Note:
  1. invoices is the table name
  2. orders is the table name
In the above snaphot, the motive is to declare the relationship between the orders and invoices tables. It's clear that orders will have invoices, i.e., invoices belong to orders. And watch out we will be using same words. Now to have the relationship declared, we will go to their models (Remember: the application access the tables through model so it makes sense to declare relationships also in models).

Now I am into order model, orders having invoices. so the key word that we use here is has_one and then followed by the model name (Note: It is not table name, this is not plural).
has_one :invoice

Next will go to invoice model, since invoices belongs to orders we use the key word belongs_to and then followed by the model name.
belongs_to :order

Well there is not xml written for models, no xml written for relationships. But simple convention and defined keywords done the job for us.
And as you might have guessed the has_many comes into use when the orders table is having relationship with one more table (say, line_items). The below snapshot will help you to understand the syntax and it's usage.

Will look into other keywords and other relationship in the following posts...

Thursday, February 7

Hyderabad hosts BarCamp5


BarCamp what is it?
BarCamp is an international network of user generated conferences — open, participatory workshop-events, whose content is provided by participants — often focusing on early-stage web applications and related open source technologies...
and the u can read more from here...

As part of series of BarCamp, this series is held @ Hyderabad. Into details....

Theme: Social web and beyond

Technologies, demos and startups- betting on Web2.0, Social web, Semantics Web and beyond!
Entrepreneurship
Social Web and Beyond
Opensource and Emerging Technologies
Product/Prototype/Idea Demos



On February 16th, 2008. Saturday

Venue ( Map of the venue )
Block 1, DivyaSree Omega
Survey No. 13, Kondapur Village,
Hyderabad, A.P 500 032
India.

Register @ Barcamp and hope to meet you there!
@ Orkut
@ Facebook

Spread the word and get the most of it!

Monday, February 4

ActiveRecord - Pluralization convention

In the previous post, we had seen how simply we had connected our database to the application. Now let us look in to another convention wherein, you need not have a xml file to connect each table in the database to the classes (Note: class is the blue print from where we create objects) in our application.
The convention here followed is English way of singular and plural forms. The database is nothing but collection of records, data in specific structure. And a 'class' as per Object Oriented Paradigm, it is a constructor and you can have multiple objects of similar type from it!
So it absolutely makes sense to name our tables in plural form (collection of data) and a class in the singular form.
Rails just does that! we name the tables of database as plurals and the respective classes as singular form of the same.

The above snapshot is taken from David's book on rails. As it shown here, we maintain the singular form on to the class names and plural on the table names.
Rails literally understands the singular and plural form of the words you use.

Order orders
Person people

You take a note of the way we write the names:
  • the table names in plural form all lower case letters.
  • the class name in singular form with camel case/capitalized word
Of course, I am sure you have few questions running into your mind:
  1. What if the word does not have proper plural form?
  2. What if I do not want to follow this?
The answers are:
  1. As you can see in the above snapshot, the 'Person' as the class name and 'people' as the table name. And if you do not have proper/matching form for it, or you did not maintain the convention mentioned - you can use a keyword called set_table_name, in the model class where ever you are defining the construct.
  2. You can disable this feature globally with a variable under 'config/environment.rb' of the application. ActiveRecord::Base.pluralize_table_names = false
Well, this is just a convention that help avoid writing/maintaining lot of xml files and connection problems. Let me also tell you that it is not mandatory to have this maintained strictly.
I guessed only the above questions, if you have more questions touch base with me and get them clarified.

Tuesday, January 29

ActiveRecord Databases - II

In the previous post, I just shown how do you tell your application the whereabouts of the database(s) that's in use. Now we are left out with task to connect each tables. Let me remind you again, this would need configuring/customizing lots of xml files in java based applications.
You may ask:
Come on, How do you achieve it without the xml files?
Well the magic here is usage of, pluralisation of tables and respective singular form for it's class names.

Can you show me how to do it?
hmmm... of course.
In last post we modified database.yml of our "dummy" project.

adapter: mysql
database: dummy
username: root
password:
host: localhost

Just recollect, this shows our "dummy" project is referencing to database by name "dummy". I am creating the database related tables, objects (rows), columns (properties) using a tool called phpMyAdmin.

Assuming that this "dummy" database contains a table with user information. So our convention would suggest to have table name in plural form. Let's call it as "users". Now we need to have a class created with singular form of the "users" -> "user", and respective logic relating to the table would go into/under this class.
class User <>

end

Let us diagnose a bit the above code. Recollect the convention we talked above, and the ORM concept. This means that the applications having class called "User" which would connect/contact to database table by name "users" (the database info is set up in database.yml).

We will slowly getting into the code and we keep developing or adding more functionalities to our "dummy" project.

Do I need to use only mysql as the database?
Not exactly and need not be. The following table would give the info related to configure each database and the respective parameters:


Well more action and fun is on the way :)