File: csv.rb

package info (click to toggle)
ruby-tilt 2.6.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 648 kB
  • sloc: ruby: 4,998; makefile: 7
file content (53 lines) | stat: -rw-r--r-- 1,105 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# frozen_string_literal: true
require_relative 'template'
require 'csv'

module Tilt

  # CSV Template implementation. See:
  # http://ruby-doc.org/stdlib/libdoc/csv/rdoc/CSV.html
  #
  # == Example
  #
  #    # Example of csv template
  #    tpl = <<-EOS
  #      # header
  #      csv << ['NAME', 'ID']
  #
  #      # data rows
  #      @people.each do |person|
  #        csv << [person[:name], person[:id]]
  #      end
  #    EOS
  #
  #    @people = [
  #      {:name => "Joshua Peek", :id => 1},
  #      {:name => "Ryan Tomayko", :id => 2},
  #      {:name => "Simone Carletti", :id => 3}
  #    ]
  #
  #    template = Tilt::CSVTemplate.new { tpl }
  #    template.render(self)
  #
  class CSVTemplate < Template
    self.default_mime_type = 'text/csv'

    def prepare
      @outvar = @options.delete(:outvar) || '_csvout'
    end

    def precompiled_template(locals)
      <<-RUBY
        #{@outvar} = CSV.generate(**#{@options}) do |csv|
          #{@data}
        end
      RUBY
    end

    def precompiled(locals)
      source, offset = super
      [source, offset + 1]
    end

  end
end