Friday, January 8, 2010

Truncate string in ruby

I was looking for a ruby method in my Ruby on Rails project which can truncate a string, say after 50 characters.

I found 'truncate' method, which is a rails api method for truncating string in views.
So if have string
str = "Hi, this is Gourav Tiwari, how are you??" # total 40 characters
the truncate method can be used in the ciew like this:
truncate(str, :length => 25, :ommision => " - - -")
and the result would be :
"Hi, this is Gourav Tiwari, - - -"

In ruby I can accomplish same by slice and concatenation:
myproject>ruby script\console
>> str = "Hi, this is Gourav Tiwari, how are you??"
=> "Hi, this is Gourav Tiwari, how are you??"
>> str.slice(0..25)
=> "Hi, this is Gourav Tiwari,"
>> str.slice(0..25) + " - - -"
=> "Hi, this is Gourav Tiwari, - - -"

Very simple!

Thursday, January 7, 2010

Fixing invisible pages in JQGrid

Playing more on JQgrid plugin from 2dconcept, I faced a strange issue. Sometimes it skips some pages.

For example if you have total 15 pages, and you navigate till 6th page and then you hit next page button on the grid, it will not show you the 7th page! you have to click next page button once more to see the 8th page. So where the 7th page is gone?


No, it's not invisible, it's all hidden in json response.

When I saw the response for page 7 (using firbug), it was coming well, but the grid was not showing the 7th page at all. I dug into the library file more and figured out that, if in the response you have a double quote, it will not display that page.

Say you have this json response:
{"page":"1","total":1,"records":"1","rows":[{"id":"7","cell":["gourav tiwari hel"lo!","this","should","be right!"]}]}
 

See the double quote in the response.
 

I tried using to_json library method, but it actually removes all the double quotes, even the necessary ones as well. So not a good idea. I extended to_jqgrid_json method like this:
module JqgridJson
def to_jqgrid_json(attributes, current_page, per_page, total)
json = %Q({"page":"#{current_page}","total":#{total/per_page.to_i+1},"records":"#{total}")
if total > 0
json << %Q(,"rows":[)
each do |elem|
elem.id ||= index(elem)
json << %Q({"id":"#{elem.id}","cell":[)
couples = elem.attributes.symbolize_keys
attributes.each do |atr|
value = get_atr_value(elem, atr, couples)
value = value.is_a?(String) ? value.gsub(/"/, '\"') : value # added this line
json << %Q("#{value}",)
end
json.chop! << "]},"
end
json.chop! << "]}"
else
json << "}"
end
end
end

And the response become this:
{"page":"1","total":1,"records":"1","rows":[{"id":"7","cell":["gourav tiwari hel\"lo!","this","should","be right!"]}]}

 
No invisible page in JQGrid anymore!