Sha256: 41de3664ac9dab5ef1d6325171d50ccfad77bc179df0eba60498d18e9d3ce386

Contents?: true

Size: 1.72 KB

Versions: 1

Compression:

Stored size: 1.72 KB

Contents

module TablePal
  class Table

    attr_reader :validations, :rows, :columns, :cells_by_row_and_column, :cells_by_column

    def initialize(validations: false)
      @validations             = validations
      @rows                    = []
      @columns                 = []
      @cells_by_column         = {}
      @cells_by_row_and_column = {}
    end

    def create_row(options = {})
      Validate.new(__method__, options) if validations

      Row.new(options.merge(table: self)).tap do |row|
        @rows << row
      end
    end

    def create_underline
      Row.new(table: self).cells_as_underline
    end

    def create_column(options = {})
      Validate.new(__method__, options) if validations

      Column.new(options.merge(table: self)).tap do |column|
        cells_by_column[column] = []
        @columns << column
      end
    end

    def create_cell(options = {})
      Validate.new(__method__, options) if validations

      row    = options[:row]
      column = options[:column]

      ensure_cell_does_not_exist(row: row, column: column)

      Cell.new(options).tap do |cell|
        cells_by_column[column] << cell
        cells_by_row_and_column[key(options)] = cell
      end
    end

    def find_cell(options)
      cells_by_row_and_column[key(options)]
    end

    def key(options)
      {
        row:    options[:row],
        column: options[:column]
      }
    end

    def select_cells(column:)
      cells_by_column[column]
    end

    def ensure_cell_does_not_exist(row:, column:)
      return unless validations

      cell = find_cell(row: row, column: column)

      return unless cell

      raise TablePalError, "Cell with content: '#{cell.content}' already exists at this row and column."
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
table_pal-0.3.3 lib/table.rb