Sha256: 6778b607e60c64fe31a70f2f2ca284d26f4de87ddd01222068cb471b552d0695

Contents?: true

Size: 1.32 KB

Versions: 1

Compression:

Stored size: 1.32 KB

Contents

# frozen_string_literal: true

module Columnify
  class Worksheet
    def initialize(resources, *args)
      @options = args.extract_options!
      @column_names = @options[:column_names].presence || args
      @attributes = args
      @resources = resources
      @buffer = StringIO.new
      @workbook = Spreadsheet::Workbook.new
    end

    def create
      inject_column_names
      inject_data
      write_workbook_buffer
      read
    end

    private

    def read
      @buffer.rewind
      @buffer.read
    end

    def write_workbook_buffer
      @workbook.write(@buffer)
    end

    def inject_column_names
      sheet.row(0).concat humanized_columns
    end

    def inject_data
      @resources.each_with_index do |resource, index|
        sheet.column(index).default_format = cell_format
        @attributes.each do |method_name|
          sheet.row(index + 1).default_format = cell_format
          sheet.row(index + 1).push(resource.send(method_name))
        end
      end
    end

    def cell_format
      @cell_format ||= Spreadsheet::Format.new text_wrap: true
    end

    def humanized_columns
      @humanized_columns ||= @column_names.map(&:to_s).map(&:humanize)
    end

    def sheet
      @sheet ||= @workbook.create_worksheet(name: worksheet_name)
    end

    def worksheet_name
      Time.now.to_i.to_s
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
columnify-0.1.1 lib/columnify/worksheet.rb