Making a sortable, dynamic grid
I came up against an interesting challenge on a current project. This was actually pretty fun to figure out. Here is what I came up with.
I needed to display a grid with columns and rows that had information in each cell. The information in the cells needed to be dynamic, or change based on a UI perspective.
Also, if there were more than 10 rows in a column, the remaining cells needed to wrap to the next column.
This is definitely a job for a helper so I wrote these methods for the helper to render this sortable, dynamic grid. So far it seems to be holding up when rendering grids of various columns and rows.
-
-
def my_grid
-
@my_data = ”
-
@my_data += ‘<table>’
-
@my_data += ‘<tr>’
-
-
num = 1
-
#this starts a new column for each category
-
@columns.each do |col|
-
cell = Cell.find(:all, :conditions => [‘category_id = ?’, col]) rescue nil
-
-
count = cell.size
-
item = 0
-
itemtotal = 1
-
cell.each do |row|
-
#if this is the 0 item start a new column
-
if item == 0
-
@my_data += self.start_col
-
end
-
-
score = row.get_my_score(row.id, @grid, @user).to_s
-
@my_data += self.list_item(score, row, itemtotal)
-
-
#if this is the 9th item, or is the last of the cells, close the column and reset count
-
item += 1
-
if item == 10 || itemtotal == count
-
@my_data += self.end_col(num)
-
num = num.to_i + 1
-
item = 0
-
end
-
itemtotal += 1
-
end
-
-
-
end
-
-
@my_data += ‘</tr>’
-
@my_data += ‘</table>’
-
#return @my_data
-
end
-
-
-
def start_col
-
@start = ‘<td valign="bottom"><div style="position: relative; bottom: 0px; display: block;">’
-
@start += ‘<ul style="vertical-align: bottom">’
-
return @start
-
end
-
-
-
def end_col(num)
-
@end = ‘</ul>’
-
@end += num.to_s
-
@end += ‘</td>’
-
return @end
-
end
-
-
-
def list_item(score, row, item)
-
@list = ‘<li class=key_’+ score +‘>’
-
#some stuff here…
-
@list += ‘</li>’
-
return @list
-
end
-