table snippets

Populating a table with n checkbox fields

Tagged table, checkbox, populating, enumerator, in_groups_of  Languages ruby

Let's say you have 10 checkboxes and you want to display 4 per line as shown here:

x  x  x  x
x  x  x  x
x  x

This can be achieved with the following code:

    from = 0
    to   = checkboxes.size
    cols = 4

    from.step(to, cols) do |i| 
    <% for checkbox in checkboxes.slice(i..i + (cols -1)) %>
        <td><input type="checkbox" id="<%= %>" name="column" value="<%= checkbox.value %>"/> <label for="<%= %>"><%=></label></td>
    <% end %>
<% end %>

If you're using Rails you can also use the built in method described here.

%w(1 2 3 4 5 6 7).in_groups_of(3) {|g| p g}
["1", "2", "3"]
["4", "5", "6"]
["7", nil, nil]

You can also use the Enumerator class

How to convert a HTML table to CSV or JSON

Tagged csv, html, table, json  Languages ruby
require 'nokogiri'
require 'net/http'
require 'csv'
require 'json'

url = 'http://site/html.table'
uri = URI(url)
response = Net::HTTP.get(uri)

doc = Nokogiri::HTML(response)
table = doc.xpath('//table//tr').map do |row|
  row.xpath('td').map do |cell|
puts JSON.pretty_generate(table)