Class: TableSchema::Table

Inherits:
Object
  • Object
show all
Defined in:
lib/tableschema/table.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source, schema: nil, csv_options: {}) ⇒ Table

Returns a new instance of Table.



8
9
10
11
12
13
14
15
16
17
# File 'lib/tableschema/table.rb', line 8

def initialize(source, schema: nil, csv_options: {})
  @csv_options = csv_options.merge(headers: true)
  @csv = parse_csv(source)
  @descriptor = schema
  @headers = initialize_headers
  if !@descriptor.nil?
    @schema = TableSchema::Schema.new(@descriptor)
    initialize_unique_colums
  end
end

Instance Attribute Details

#headersObject (readonly)

Public



6
7
8
# File 'lib/tableschema/table.rb', line 6

def headers
  @headers
end

#schemaObject (readonly)

Public



6
7
8
# File 'lib/tableschema/table.rb', line 6

def schema
  @schema
end

Instance Method Details

#inferObject



47
48
49
50
51
52
53
54
55
# File 'lib/tableschema/table.rb', line 47

def infer()
  if !@schema
    inferer = TableSchema::Infer.new(@headers, @csv)
    @schema = inferer.schema
    initialize_unique_colums
    @csv.rewind
  end
  @schema.descriptor
end

#iter(keyed: false, cast: true, limit: nil) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/tableschema/table.rb', line 19

def iter(keyed: false, cast: true, limit: nil)
  unless block_given?
    return enum_for(:iter, limit: limit, cast: cast, keyed: keyed)
  end

  @csv.each_with_index do |row, i|
    break if limit && (limit <= i)
    if cast == true
      cast_values = @schema.cast_row(row)
      row = CSV::Row.new(@headers, cast_values)
      check_unique_fields(row, i)
    end
    if keyed == true
      yield row.to_h
    else
      yield row.fields
    end
    collect_unique_fields(row, i)
  end

  @csv.rewind
end

#read(keyed: false, cast: true, limit: nil) ⇒ Object



42
43
44
45
# File 'lib/tableschema/table.rb', line 42

def read(keyed: false, cast: true, limit: nil)
  iterator = self.iter(keyed: keyed, cast: cast, limit: limit)
  iterator.to_a
end

#save(target) ⇒ Object



57
58
59
60
61
62
63
# File 'lib/tableschema/table.rb', line 57

def save(target)
  CSV.open(target, "wb", @csv_options) do |csv|
    csv << @headers
    self.iter{ |row| csv << row }
  end
  true
end