bookmark_bordersudo: giving previlige to non previliged users

On *nix systems, there are certain tasks such as running servers, editing sensitive resource or configuration files that only privileged users can do.

During software development phase, many such tasks need to be repeated often, and the application developer needs to request the system administrator each time. Sudo is a perfect tool for such times. ( atleast that is how I came across it)

The root user can specify users or group, and command which they can execute in the /etc/sudoers file. The non previliged user can then use sudo to run commands as previliged users, without loggin in as one. (without the need to know the previliged user’s password that is). Root users should use visudo to edit the /etc/sudoers file. Visudo parses the file for any syntax error.

An additional benefit of using sudo is that it logs each time a user tries to run a sudo command.

You can read more about sudo here or do a man sudo.

bookmark_borderDRY in Views

Don’t Repeat yourself while creating Views in Rails.

I was confused when I starting working on Rails … but now I apply these rules.

Use Layouts to create page layouts to be shared by all views rendered by a controller.

Use components to create controller actions whose output needs to be used more than once

Use partials to create views, which need to be rendered more than once, in the same action or in different actions. [see collection option to render partial more than once in the same action]

bookmark_borderruby code block and iterators

Code Blocks and Iterators are a very useful feature in Ruby.

An iterator is a method that executes a block of code.

Say we have a method named each


def each(array)
    #do something
end

The block is specified next to the method call, after the last parameter to the method.


names=['alice', 'bob', 'charlie', 'dave']
each(names) { |s|  puts s }

Our block is the code within the { } braces. (mutiple line block can be written between do….end)

We are passing an array names, in the call each(names).
Inside each() we will iterate through this array names.


def each(arr) 
  for i in 0..arr.size-1 
    yield arr[i] 
  end 
end 

All the code block iterator’s magic is done by the yield statement.

The yield statement invokes the code in the block.
The yield statement can also pass parameters to the block . In our example, the array element at position i is passed to the block. The block receives this parameter between vertical bars or pipes. (|s| in our example)

A block may also return value to the yield. The last expression evaluated in the block is passed back as the value of the yield.

Here is the complete listing of our code so far


def each(arr) 
  for i in 0..arr.size-1 
    yield arr[i] 
  end 
end 
names=['alice', 'bob', 'charlie', 'dave']
each(names) { |s| puts s } 

This code will print all the array elements, as yield is called for each array element. Yield in turn invokes the code block passing it the array elements, the code block puts the element.

We could change the block code to print all the array element in upper case or in reverse.


each(names) { |s| puts s.upcase } 
each(names) { |s| puts s.reverse } 

What we have done so far, is actually provided builtin by ruby for various types of collections.

each is a builtin iterator in ruby which yield the elements of the collection.
To print all elements of array names we could simply do


names.each { |name|  puts name }

Similarly there is a find iterator.
To print all names that begin with m, we could use


m_names = names.find { |name| name.index('m') == 0 } 
m_names.each { |name| puts name } 

Iterators help a lot in keeping ruby on rails code compact. I have been using them a lot, ever since i discovered them.

bookmark_borderRails:join table name

I just came across the naming convention for a has_and_belongs_to_many relation’s join table.

If you have tables products and categories, which have a many to many relationship, a product can belong to many categories and a category can contain many products. What would you name the joining table, products_categories or categories_products.

Rails convention says use categories_products.

Rails assumes that a join table is named after the two tables it joins (with the names in alphabetical order). If you use some other name, you would need an additional declaration.

Unless there is a very compelling reason to do so, one should stick with the convention.
Reason: For maximum productivity don’t go against Rails’ philosophy “Convention over configuration”

bookmark_borderRails: Automatic Time Stamping

I tried this with mySQL. Should work with other databases too.

If you have columns named “created_at” or “updated_at” of type datetime in your database table,
Rails will automatically insert the value of now( ), in the column “created_at” when a model corresponding to the table is saved in the database. Similarly it will automatically update the value of the column “updated_at” to the value of now( ), when a model is updated and saved to the database.

“created_on” and “updated_on”, of type date, display the same functionality.

One of the basic Rails philosophy is “Convention over Configuration”, meaning that rails has sensible defaults for a lot of aspects.

If the programmer follows these naming conventions a lot of functionality in the application gets built-in by default.

bookmark_borderRails: avoid empty lines in generated html

Normally embedded Ruby code (Erb) in views that does not generate any output, leaves empty blank lines in the generated HTML code. These are embedded ruby lines in rhtml files which begin with < % and not <%=. To avoid generating these empty blank lines, end the embedded ruby code with -%>, the others will be ended as %>. The extra minus sign (-) at the end, will suppress the blank lines.

bookmark_borderRails: Escaping html entities

Many times data entered on the screen by a user, or data fetched from the db, contains less than (<), greater than (>), ampersand (&) and quotes etc. These characters have special meaning in html. And if these are passed in the view as such, they may garble the browser display.

The h() method prevents these characters in strings from garbling the browser display. The h() method escapes them as html entities.

h() method in rails does the same thing as htmlentities() does in php.

Update [17th Jan 2006] I just learnt that long name of h() is html_escape()

bookmark_borderWordPress as CMS

I have been using wordpress for some time now, writing small modules and themes as well.
This blog also runs on wordpress.

Recently for a client, I wanted a content management system. I studied creation of pages at wordpress codex site and found it had everything that I needed.
Page creation, individual themes for pages, page list for navigation menu, nesting of pages, everything i needed for the client, so that the ultimate control over the content and style remains with the client.

I was so impressed that i decided to setup my company site also in wordpress. And while doing so, I thought it would be good to add blog as a feature of my company site.
The site is at http://vinsol.com .
By and large the structure is there, I need to add a lot of content though.

It is a site which is very proudly powered by WP.

bookmark_borderCustomizing Rails validation error messages

Rails Version information: activerecord-1.12.1, rails-0.14.1

I have a form, where the user enters a name, “johndoe”. I already have a user “johndoe”, and i want user name to be unique.
The default error message that validate_uniqueness_of returns is “Name is already taken”
But I want “Name johndoe is not available”.

Here is my user model, user.rb file, with the custom message.

Continue reading “Customizing Rails validation error messages”