Saturday, February 08, 2014

PUT and PATCH in REST (Rails)

In Rails framework, As a developer we know what is "PUT" request and where to use it.

Right!  "PUT" is one of the four http verbs which we use to deal with resource in REST.  we use it for updating a resource.

But Using "PUT" to "UPDATE" a resource is wrong in many cases (almost in all update cases in Rails).  Let me explain it why...

As per the HTTP standards document RFC 5789 (,  HTTP PUT method only allows a complete replacement of a document (resource).
Look at this phrase ---> 'complete replacement' , Now you can understand why "PUT" is not the correct method to update a resource in Rails. If you are still not clear, then read below.

When we update a resource in Rails, the requesting client will never replace the resource completely. We are doing partial updates only like for example, when updating an Active Record model, Rails sets the attribute "updated_at" timestamp, not the requesting client.

So to follow proper HTTP semantics, we should always use "PATCH" method instead of "PUT" to update a resource. The cool thing about "PATCH" is it will support both "Partial" and "Complete" updates.

Good news for Rails developers ->  Rails 4 came with "PATCH" verb support for "UPDATE" operations. (Dont worry, its still supporting the old "PUT" method too, but we should avoid using "PUT" moving forward)

Thursday, September 05, 2013

Changing Ruby in Sublime Text 2 (Ubuntu)

 In Ubuntu, the default ruby build in Sublime Text Editor will use the system ruby.

So If you want to use a different ruby version for your Sublime Text 2 editor, then you can do the following things to acheive it.

Assuming that you are using rvm already (if no, please install rvm first :)

Step 1:

Go to Terminal and create a rvm wrapper for Sublime Editor like below
rvm wrapper <ruby> <wrapper_name>

 rvm wrapper ruby-1.9.3-p325 sublime_ruby
Step 2:

Open Sublime Text Editor and Go to Preferences -> Browse Packages

 This will open a file browser where you can see lot of packages used by Sublime Text Editor

Step 3:

In that file browser, you can see a folder called "Ruby".
Inside that "Ruby" folder, you can find a file called "Ruby.sublime-build"

Step 4:

Edit this file "Ruby.sublime-build" like below and save it

Note:  Please replace "user" with your actual username
 "cmd": ["/home/user/.rvm/bin/sublime_ruby", "$file"],
 "file_regex": "^(...*?):([0-9]*):?([0-9]*)",
 "selector": "source.ruby"
Step 5:

Quit your Sublime Editor and open it again. Now you can see the new ruby version loaded into the Sublime Text Editor.

Monday, August 31, 2009

creating images from unicode text using rmagick

To create images from the unicode text, we can use the "encoding" method for the Draw object.


require "RMagick"

def show_textimg
bg =,20){self.background_color = "#9E9E9E"}
text =
text.encoding = "Unicode"
bg.write "#{RAILS_ROOT}/public/images/text.jpg"

Monday, January 28, 2008

Top Ten Mistakes in Web Design

Top Ten Mistakes in Web Design

1. Bad Search

Overly literal search engines reduce usability in that they're unable to handle typos, plurals, hyphens, and other variants of the query terms. Such search engines are particularly difficult for elderly users, but they hurt everybody.
A related problem is when search engines prioritize results purely on the basis of how many query terms they contain, rather than on each document's importance. Much better if your search engine calls out "best bets" at the top of the list -- especially for important queries, such as the names of your products.
Search is the user's lifeline when navigation fails. Even though advanced search can sometimes help, simple search usually works best, and search should be presented as a simple box, since that's what users are looking for.

2. PDF Files for Online Reading

Users hate coming across a PDF file while browsing, because it breaks their flow. Even simple things like printing or saving documents are difficult because standard browser commands don't work. Layouts are often optimized for a sheet of paper, which rarely matches the size of the user's browser window. Bye-bye smooth scrolling. Hello tiny fonts.
Worst of all, PDF is an undifferentiated blob of content that's hard to navigate.
PDF is great for printing and for distributing manuals and other big documents that need to be printed. Reserve it for this purpose and convert any information that needs to be browsed or read on the screen into real web pages.

3. Not Changing the Color of Visited Links

A good grasp of past navigation helps you understand your current location, since it's the culmination of your journey. Knowing your past and present locations in turn makes it easier to decide where to go next. Links are a key factor in this navigation process. Users can exclude links that proved fruitless in their earlier visits. Conversely, they might revisit links they found helpful in the past.
Most important, knowing which pages they've already visited frees users from unintentionally revisiting the same pages over and over again.
These benefits only accrue under one important assumption: that users can tell the difference between visited and unvisited links because the site shows them in different colors. When visited links don't change color, users exhibit more navigational disorientation in usability testing and unintentionally revisit the same pages repeatedly.

4. Non-Scannable Text

A wall of text is deadly for an interactive experience. Intimidating. Boring. Painful to read.
Write for online, not print. To draw users into the text and support scannability, use well-documented tricks:
  • subheads
  • bulleted lists
  • highlighted keywords
  • short paragraphs
  • the inverted pyramid
  • a simple writing style, and
  • de-fluffed language devoid of marketese.

5. Fixed Font Size

CSS style sheets unfortunately give websites the power to disable a Web browser's "change font size" button and specify a fixed font size. About 95% of the time, this fixed size is tiny, reducing readability significantly for most people over the age of 40.
Respect the user's preferences and let them resize text as needed. Also, specify font sizes in relative terms -- not as an absolute number of pixels.

6. Page Titles With Low Search Engine Visibility

Search is the most important way users discover websites. Search is also one of the most important ways users find their way around individual websites. The humble page title is your main tool to attract new visitors from search listings and to help your existing users to locate the specific pages that they need.
tag and is almost always used as the clickable headline for listings on search engine result pages (SERP). Search engines typically show the first 66 characters or so of the title, so it's truly The page title is contained within the HTML microcontent.
Page titles are also used as the default entry in the Favorites when users bookmark a site. For your homepage, begin the with the company name, followed by a brief description of the site. Don't start with words like "The" or "Welcome to" unless you want to be alphabetized under "T" or "W."
For other pages than the homepage, start the title with a few of the most salient information-carrying words that describe the specifics of what users will find on that page. Since the page title is used as the window title in the browser, it's also used as the label for that window in the taskbar under Windows, meaning that advanced users will move between multiple windows under the guidance of the first one or two words of each page title. If all your page titles start with the same words, you have severely reduced usability for your multi-windowing users.
Taglines on homepages are a related subject: they also need to be short and quickly communicate the purpose of the site.

7. Anything That Looks Like an Advertisement

Selective attention is very powerful, and Web users have learned to stop paying attention to any ads that get in the way of their goal-driven navigation. (The main exception being text-only search-engine ads.)
Unfortunately, users also ignore legitimate design elements that look like prevalent forms of advertising. After all, when you ignore something, you don't study it in detail to find out what it is.
Therefore, it is best to avoid any designs that look like advertisements. The exact implications of this guideline will vary with new forms of ads; currently follow these rules:
  • banner blindness means that users never fixate their eyes on anything that looks like a banner ad due to shape or position on the page
  • animation avoidance makes users ignore areas with blinking or flashing text or other aggressive animations
  • pop-up purges mean that users close pop-up windoids before they have even fully rendered; sometimes with great viciousness (a sort of getting-back-at-GeoCities triumph).

8. Violating Design Conventions

Consistency is one of the most powerful usability principles: when things always behave the same, users don't have to worry about what will happen. Instead, they know what will happen based on earlier experience. Every time you release an apple over Sir Isaac Newton, it will drop on his head. That's good.
The more users' expectations prove right, the more they will feel in control of the system and the more they will like it. And the more the system breaks users' expectations, the more they will feel insecure. Oops, maybe if I let go of this apple, it will turn into a tomato and jump a mile into the sky.
Jakob's Law of the Web User Experience states that "users spend most of their time on other websites."
This means that they form their expectations for your site based on what's commonly done on most other sites. If you deviate, your site will be harder to use and users will leave.

9. Opening New Browser Windows

Opening up new browser windows is like a vacuum cleaner sales person who starts a visit by emptying an ash tray on the customer's carpet. Don't pollute my screen with any more windows, thanks (particularly since current operating systems have miserable window management).
Designers open new browser windows on the theory that it keeps users on their site. But even disregarding the user-hostile message implied in taking over the user's machine, the strategy is self-defeating since it disables the Back button which is the normal way users return to previous sites. Users often don't notice that a new window has opened, especially if they are using a small monitor where the windows are maximized to fill up the screen. So a user who tries to return to the origin will be confused by a grayed out Back button.
Links that don't behave as expected undermine users' understanding of their own system. A link should be a simple hypertext reference that replaces the current page with new content. Users hate unwarranted pop-up windows. When they want the destination to appear in a new page, they can use their browser's "open in new window" command -- assuming, of course, that the link is not a piece of code that interferes with the browser’s standard behavior.

10. Not Answering Users' Questions

Users are highly goal-driven on the Web. They visit sites because there's something they want to accomplish -- maybe even buy your product. The ultimate failure of a website is to fail to provide the information users are looking for.
Sometimes the answer is simply not there and you lose the sale because users have to assume that your product or service doesn't meet their needs if you don't tell them the specifics. Other times the specifics are buried under a thick layer of marketese and bland slogans. Since users don't have time to read everything, such hidden info might almost as well not be there.
The worst example of not answering users' questions is to avoid listing the price of products and services. No B2C ecommerce site would make this mistake, but it's rife in B2B, where most "enterprise solutions" are presented so that you can't tell whether they are suited for 100 people or 100,000 people. Price is the most specific piece of info customers use to understand the nature of an offering, and not providing it makes people feel lost and reduces their understanding of a product line. We have miles of videotape of users asking "Where's the price?" while tearing their hair out.
Even B2C sites often make the associated mistake of forgetting prices in product lists, such as category pages or search results. Knowing the price is key in both situations; it lets users differentiate among products and click through to the most relevant ones.

Source :

Friday, January 04, 2008

'send' in Ruby


Calling a method when method name is stored as a string object in a variable i.e. you can not see which method to call.

example 1
when method name is simply stored as a String object

  1. class C
  2. def wish
  3. p "hello world"
  4. end
  5. end
  6. a = "wish"
  7. c =
  8. c.send(a)

example 2
making set method at runtime

  1. class C
  2. attr_accessor :name
  3. end

  4. c =

  5. a = "name"

  6. c.send(a + "=", "Arun")

  7. p c.send(a)

example 3
this is interesting, when attribute name itself is send

  1. class C
  2. attr_accessor :send
  3. end

  4. c =

  5. a = "send"

  6. c.__send__(a + "=", "Arun")

  7. p c.__send__(a) # => Arun

Thursday, November 29, 2007

Difference between Strings and Symbols in Ruby

Symbols have two nice properties compared to strings which can save you memory and CPU time:


For every unique string value, there is a unique symbol object. Three strings with the same value can use up to three times the memory of three symbols with the same value. This is because those three symbols are actually the same object.

p "blah".object_id #=> -605600196
p "blah".object_id #=> -605618816
p "blah".object_id #=> -605637168
p :blah.object_id #=> 4071694
p :blah.object_id #=> 4071694
p :blah.object_id #=> 4071694
p "blah".to_sym.object_id #=> 4071694
p "blah".to_sym.object_id #=> 4071694
p "blah".to_sym.object_id #=> 4071694
I think now you can understand

Symbol objects are created on-demand behind the scenes for new unique string values. Once a symbol exists for a particular string value, it will continue to be used for that value rather than creating more symbols for it.

Of course, this has a disadvantage: Ruby keeps symbols around forever (well, until the end of your program anyway), in case they are needed again.

That’s fine if the number of unique symbols is relatively small and you expect to keep reusing them. However, if you have an unlimited number of string values, and/or you only use each one briefly (for example, lines arriving on an input stream), symbols are not the tool for you. You’ll just use up all your memory.

CPU Time

Testing two symbol values for equality (or non-equality) is faster than testing two string values for equality, because Ruby only needs to do a single test. Checking two strings for equality is more complicated; every individual character in the string has to be checked until a difference is found.

As noted above, each unique string value has an associated symbol. This means that checking whether two symbols have the same string value or not is as simple as checking whether they are the same object or not.

One comparison:

:Worcestershire == :Worcestershire

Easy peasy. They’re the same object, so they’re equal.

Sixteen comparisons:

"Worcestershire" == "Worcestershire"

With strings, Ruby has to dig into the objects to check their contents. Since in this case they’re different string objects with the same length, it’s got to check all fourteen characters in each string to make sure that they really are equal.

However, what symbols don’t give you is lexical comparison. You can do "foo" > "bar", but not :foo > :bar. They’re digested. Their original string values are a memory which can be resurrected only via Symbol#to_s.

The Right Tool for the Job

If you have a modest number of unique string values that you want to use over and over, and will mostly be using them as-is (i.e. not concatenating them, uppercasing them, etc….), then symbols are the right tool for you.

Method names (such as those given to Module#attr_reader, or Object#send) are a good example of this; in fact, Ruby uses symbols internally to remember method, variable, and constant names.

Otherwise, stick with strings. Strings are not that much slower than symbols, and many times the extra limitations of symbols aren’t worth it.

Wednesday, November 14, 2007

Rails 2.0 - Preview Release

Its time to feel the Real Power of Rails.
The Rails 2.0 preview version is just released.

I've listed down some of the important updates of Rails 2.0 here

Action Pack - Multiview

In Rails 2.0, the format of the template is separated from its rendering engine. So show.rhtml now becomes show.html.erb, which is the template that’ll be rendered by default for a show action that has declared format.html in its respond_to. And you can now have something like show.csv.erb, which targets text/csv, but also uses the default ERB renderer.

So the new format for templates is action.format.renderer. A few examples:

  • show.erb: same show template for all formats
  • index.atom.builder: uses the Builder format, previously known as rxml, to render an index action for the application/atom+xml mime type

Action Pack: Record identification

Piggy-backing off the new drive for resources are a number of simplifications for controller and view methods that deal with URLs. We’ve added a number of conventions for turning model classes into resource routes on the fly. Examples:

# person is a Person object, which by convention will
# be mapped to person_url for lookup
link_to(, person)

Action Pack: HTTP Loving

New module is added in Rails 2.0 to work with HTTP Basic Authentication, which turns out to be a great way to do API authentication over SSL. It’s terribly simple to use. Here’s an example (there are more in ActionController::HttpAuthentication):

class PostsController < password = "dhh" except =""> [ :index ]

def index
render :text => "Everyone can see me!"

def edit
render :text => "I'm only accessible if you know the password"

def authenticate
authenticate_or_request_with_http_basic do |user_name, password|
user_name == USER_NAME && password == PASSWORD

Active Record: Sexy migrations

There’s a new alternative format for declaring migrations in a slightly more efficient format. Before you’d write:

create_table :people do |t|
t.column, "account_id", :integer
t.column, "first_name", :string, :null => false
t.column, "last_name", :string, :null => false
t.column, "description", :text
t.column, "created_at", :datetime
t.column, "updated_at", :datetime

Now you can write:

create_table :people do |t|
t.integer :account_id
t.string :first_name, :last_name, :null => false
t.text :description

And hundreds upon hundreds of other improvements

We’ve got literally hundreds of bug fixes, tweaks, and feature enhancements crammed into Rails 2.0. All this coming off the work of tons of eager contributors working tirelessly to improve the framework in small, but important ways.

So how do I upgrade?

If you want to move your application to Rails 2.0, you should first move it to Rails 1.2.3. That’ll include deprecation warnings for most everything we yanked out in 2.0. So if your application runs fine on 1.2.3 with no deprecation warnings, there’s a good chance that it’ll run straight up on 2.0. Of course, if you’re using, say, pagination, you’ll need to install the classic_pagination plugin. If you’re using Oracle, you’ll need to install the activerecord-oracle-adapter gem. And so on and so forth for all the extractions.

To install the preview release through gems, do:

gem install rails --source

To try it from an SVN tag, use:

rake rails:freeze:edge TAG=rel_2-0-0_PR

Thanks to
David Heinemeier Hansson and the core team of committers and hundreds of open-source contributors