Using CSV data in Middleman

Middleman allows you to specify data in yaml format, as explained in the Data Files page. However, certain data is best represented in CSV (comma separated value).

Fortunately, it is relatively simple to write a middleman extension to read csv data.

Installation

Create a lib directory in the root of your project, if it does not exist yet.

Put the following code in the lib directory:

class CSV_Helpers < Middleman::Extension
  def initialize(app, options_hash={}, &block)
    super
  end
  helpers do
    def csv_data(file)
      csv_data = File.read(File.join(app.config[:data_dir], file))
      hash = CSV.new(csv_data, :headers => true, :header_converters => :symbol)
      return hash.to_a.map { |row| row.to_hash }
    end
  end
end
::Middleman::Extensions.register(:csv_helpers, CSV_Helpers) 

You can download the csv_helpers.rb file, if you prefer.

Put the following code in config.rb:

require 'lib/csv_helpers.rb'
activate :csv_helpers 

Usage

Suppose you have a file weight.csv in the data directory, containing entries such as:

date,weight
2015-05-20,86.5
2015-05-29,88.2

Then, if you want to print the entries in a page, use the following code:

<% csv = csv_data('weight.csv') %>
<% csv.each do |entry| %>
  <%= entry[:date] %> <%%= entry[:weight] %>
<% end %>

You can download a working example: csv_helpers_example.zip.