lib/fat_table/column.rb in fat_table-0.5.2 vs lib/fat_table/column.rb in fat_table-0.5.3

- old
+ new

@@ -81,19 +81,20 @@ # nums = [35.25, 18, '35:14', '$18_321'] # col = FatTable::Column.new(header: :prices, items: nums) # col.type #=> 'Numeric' # col.header #=> :prices # col.sum #=> 18376.75 - def initialize(header:, items: [], type: 'NilClass') + def initialize(header:, items: [], type: 'NilClass', tolerant: false) @raw_header = header @header = if @raw_header.is_a?(Symbol) @raw_header else @raw_header.to_s.as_sym end @type = type + @tolerant = tolerant msg = "unknown column type '#{type}" raise UserError, msg unless TYPES.include?(@type.to_s) @items = [] items.each { |i| self << i } @@ -139,10 +140,18 @@ size - 1 end # :category: Attributes + # Is this column tolerant of type incompatibilities? If so, the Column + # type will be forced to String if an incompatible type is found. + def tolerant? + @tolerant + end + + # :category: Attributes + # Force the column to have String type and then convert all items to # strings. def force_string! # msg = "Can only force an empty column to String type" # raise UserError, msg unless empty? @@ -398,12 +407,21 @@ # :category: Constructors # Append +itm+ to end of the Column after converting it to the Column's # type. If the Column's type is still open, i.e. NilClass, attempt to fix - # the Column's type based on the type of +itm+ as with Column.new. + # the Column's type based on the type of +itm+ as with Column.new. If its + # a tolerant column, respond to type errors by converting the column to a + # String type. def <<(itm) items << convert_to_type(itm) + rescue IncompatibleTypeError => ex + if tolerant? + force_string! + retry + else + raise ex + end end # :category: Constructors # Return a new Column appending the items of other to this Column's items,