module TablePal class Cell using Colours JUSTIFICATIONS = { left: :ljust, right: :rjust, center: :center }.freeze attr_reader :row, :column, :content, :formatter, :justification, :colour def initialize(row:, column:, content: '', formatter: nil, justification: nil, colour: nil) @row = row || (raise "Row must be supplied for cell with content: '#{content}' to exist in") @column = column || (raise "Column must be supplied for cell with content: '#{content}' to exist in") @content = content @formatter = formatter || row.formatter || NoFormatting @justification = justification || row.justification || column.justification @colour = colour || row.colour || column.colour || :itself end def formatted(justified: false, coloured: false) result = format(content) result = justify(result) if justified result = colourize(result) if coloured result end def format(result) return '' if result == '' formatter.call(result).to_s end def justify(result) result.send(JUSTIFICATIONS[justification], column.width) end def colourize(result) result.send(colour) end def width @width ||= formatted.length end end end