Class: JsonTableSchema::Table

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(csv, schema, opts = {}) ⇒ Table

Returns a new instance of Table.



10
11
12
13
14
# File 'lib/jsontableschema/table.rb', line 10

def initialize(csv, schema, opts = {})
  @opts = opts
  @csv = parse_csv(csv)
  @schema = schema.nil? ? infer_schema(@csv) : JsonTableSchema::Schema.new(schema)
end

Instance Attribute Details

#schemaObject (readonly)

Returns the value of attribute schema.



4
5
6
# File 'lib/jsontableschema/table.rb', line 4

def schema
  @schema
end

Class Method Details

.infer_schema(csv, opts = {}) ⇒ Object



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

def self.infer_schema(csv, opts = {})
  JsonTableSchema::Table.new(csv, nil, opts)
end

Instance Method Details

#csv_optionsObject



21
22
23
# File 'lib/jsontableschema/table.rb', line 21

def csv_options
  (@opts[:csv_options] || {}).merge(headers: true)
end

#parse_csv(csv) ⇒ Object



16
17
18
19
# File 'lib/jsontableschema/table.rb', line 16

def parse_csv(csv)
  csv_string = csv.is_a?(Array) ? array_to_csv(csv) : open(csv).read
  CSV.parse(csv_string, csv_options)
end

#rows(opts = {}) ⇒ Object



25
26
27
28
29
30
# File 'lib/jsontableschema/table.rb', line 25

def rows(opts = {})
  fail_fast = opts[:fail_fast] || opts[:fail_fast].nil?
  rows = opts[:limit] ? @csv.to_a.drop(1).take(opts[:limit]) : @csv.to_a.drop(1)
  converted = @schema.convert(rows, fail_fast)
  opts[:keyed] ? coverted_to_hash(@csv.headers, converted) : converted
end