Incrementing and initializing counter in a view in 1 (one!) line

Ruby On Rails No Comments »

Many times I have to make a counter that starts with 1 and monotonically incremented by 1 in Rails view. The typical example is when showing a list of things like:

7.1
7.2
7.3
....

The nice trick is to make it in 1 line:

<li>7.<%= n = n + 1 rescue n = 1 %></li>

instead of initializing “n” before the loop (which requres extra line of code).

Now the question is: is this DRY enough? Is it?

Rails JSON parser vs Open Flash Chart 2

Ruby On Rails 1 Comment »

Well having multiple JSON parsers in Ruby on Rails is not a lot of fun.

Let me explain the situation. I was happily using “.to_json” (means Rails JSON parser) until I had to parse a POST request with JSON body.
I googled it like normal people do and found this:

require "json"
data = JSON.parse(input)

which worked fine until I tried my Open Flash Charts. They were blank. No error message. Nothing.
Removing the statement to require JSON fixed the issue.

I also tried

require "json/pure"

and

require "json/ext"

with similar results.

The short debugging session revealed that Ruby Open Flash Chart 2 helper is generating right JSON when Rails built-in generator is used.
When using json, json/pure or json/ext the certain characters (slashes, quotes) in a resulting string were escaped (sometimes several times) which breaks the Open Flash Charts.

The solution was to use

data = ActiveSupport::JSON.decode(input)

which is a call to parse the json string using the Rails built-in parser.

Zebra stripes for tables

Ruby On Rails No Comments »

Replacing

<tr>

with

<tr class="<%= cycle('one', 'two') %>">

in your tables will make lists easier to read.

Also apply the following css:

table tr.one td
{
background: grey;
}
table tr.two td
{
background: white;
}

Authlogic

Ruby On Rails No Comments »

After trying several Ruby on Rails authentication solutions I think that Authlogic is the best one. Authlogic can be installed as gem and as a plugin, does not require the use of generators (only optional scaffolding to save you time) and is very modular.

A very well written tutorial is here.
The github repository is here

WP Theme by Ray Hosting and brought to you by Ray Creations | Wordpress Themes
CSS XHTML