Skip to content

Instantly share code, notes, and snippets.

@benbalter
Created May 27, 2014 22:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benbalter/1601b57e273cd1a01cbb to your computer and use it in GitHub Desktop.
Save benbalter/1601b57e273cd1a01cbb to your computer and use it in GitHub Desktop.
Converts `.csv` files in a `_csvs` directory of a Jekyll site to `site.data` content
require 'csv'
module JekyllCsv
class Generator < Jekyll::Generator
def generate(site)
dir = File.expand_path "_csvs", site.source
return if site.safe && File.symlink?(dir)
entries = Dir.chdir(dir) do
Dir['*.csv']
end
entries.each do |entry|
path = File.join(dir, entry)
next if File.symlink?(path) && safe
CSV::Converters[:blank_to_nil] = lambda do |field|
field && field.empty? ? nil : field
end
# http://technicalpickles.com/posts/parsing-csv-with-ruby/
body = File.open(path).read
key = site.send(:sanitize_filename, File.basename(entry, '.*'))
csv = CSV.new(body, :headers => true, :converters => [:all, :blank_to_nil])
site.data[key] = csv.to_a.map {|row| row.to_hash }
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment