Sha256: 6d9e957def77f1d1cda036a51035ec0260c7ab58ec50271a8e35b6ddb047145b

Contents?: true

Size: 990 Bytes

Versions: 8

Compression:

Stored size: 990 Bytes

Contents

module Comma

  class Generator

    def initialize(instance, style)
      @instance = instance
      @style    = style
      @options  = {}

      if @style.is_a? Hash
        @options                  = @style.clone
        @style                    = @options.delete(:style) || :default
        @filename                 = @options.delete(:filename)
      end
    end

    def run(iterator_method)
      if @filename
        CSV_HANDLER.open(@filename, 'w', @options){ |csv| append_csv(csv, iterator_method) } and return true
      else
        CSV_HANDLER.generate(@options){ |csv| append_csv(csv, iterator_method) }
      end
    end

    private

    def append_csv(csv, iterator_method)
      return '' if @instance.empty?
      unless @options.has_key?(:write_headers) && !@options[:write_headers]
        csv << @instance.first.to_comma_headers(@style)
      end
      @instance.send(iterator_method) do |object|
        csv << object.to_comma(@style)
      end
    end

  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
comma-2.1.3 lib/comma/generator.rb
comma-2.1.2 lib/comma/generator.rb
comma-2.1.1 lib/comma/generator.rb
comma-2.1 lib/comma/generator.rb
comma-3.0.1 lib/comma/generator.rb
comma-3.0.0 lib/comma/generator.rb
comma-2.0 lib/comma/generator.rb
comma-0.5.2 lib/comma/generator.rb