Skip to content

Instantly share code, notes, and snippets.

@hrstt
Created June 25, 2011 13:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hrstt/1046490 to your computer and use it in GitHub Desktop.
Save hrstt/1046490 to your computer and use it in GitHub Desktop.
For Nanoc, csv data to html table (simple table)
module CSVUtile
## parse csv data to table tag
def csv_to_table(file_name, header = false)
csv = CSV.readlines("data/#{file_name}.csv")
table = ""
table << parse_thead(csv.shift) if header
table << parse_tbody(csv)
end
# create thead element with inner contents
def parse_thead(header)
thead = "\t<thead>\r\n"
thead << parse_tr(header, "th")
thead << "\t</thead>\r\n"
end
# create tbody element with inner contents
def parse_tbody(body)
tbody = "\t<tbody>\r\n"
body.each do |row|
tbody << parse_tr(row, "td")
end
tbody << "\t</tbody>\r\n"
end
def parse_tr(row, type ="td")
tr = "\t\t<tr>\r\n"
row.each do |col|
tr << parse_cell(col, type)
end
tr << "\t\t</tr>\r\n"
end
# parse <th>/<td> tag.
# element convert character encoding (sjis to utf8)
def parse_cell(col, type)
"\t\t\t<#{type}#{add_align_class(col)}>"+ Kconv.kconv(col.to_s, Kconv::UTF8, Kconv::SJIS) +"</#{type}>\r\n"
end
# add class name to <th>/<td> tag
# when element is numeric, add "num" class
# when element is "-", add "missing" class
def add_align_class(col)
if col.to_s =~ /[-+]?(?:[0-9]+(\.[0-9]*)?|(\.[0-9]+))([eE][-+]?[0-9]+)?/ then
" class=\"num\""
elsif col == "-"
" class=\"missing\""
end
end
# get first row from csv file.
# to show recently data
def get_first_row(file_name)
row = CSV.readlines("data/#{file_name}.csv").shift
row.map!{|cell| Kconv.kconv(cell.to_s, Kconv::UTF8, Kconv::SJIS) }
end
# get json format
def csv_to_array(file_name)
array = []
CSV.readlines("data/#{file_name}.csv").each do |row|
array << row.map!{|cell| Kconv.kconv(cell.to_s, Kconv::UTF8, Kconv::SJIS) }
end
array
end
end
include CSVUtile
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment