File: csv.rb

package info (click to toggle)
ruby-tilt 2.0.0%2Breally1.4.1-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 476 kB
  • ctags: 411
  • sloc: ruby: 3,546; makefile: 5
file content (71 lines) | stat: -rw-r--r-- 1,395 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
require 'tilt/template'

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 self.engine_initialized?
      engine
    end

    def self.engine
      if RUBY_VERSION >= '1.9.0' && defined? ::CSV
        ::CSV
      elsif defined? ::FasterCSV
        ::FasterCSV 
      end
    end

    def initialize_engine
      if RUBY_VERSION >= '1.9.0'
        require_template_library 'csv'
      else
        require_template_library 'fastercsv'
      end
    end

    def prepare
      @code =<<-RUBY
        #{self.class.engine}.generate do |csv|
          #{data}
        end
      RUBY
    end

    def precompiled_template(locals)
      @code
    end

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

  end
end