Class: Kandata::TsvFile

Inherits:
Object
  • Object
show all
Defined in:
lib/kandata/tsv_file.rb

Overview

読み込み用TSVファイル

Constant Summary collapse

RESERVED_COLUMNS =
['type'].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filename, custom_headers = nil) ⇒ TsvFile

Returns a new instance of TsvFile.



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/kandata/tsv_file.rb', line 12

def initialize(filename, custom_headers = nil)
  @table_name = File.basename(filename).sub('.tsv', '')
  validate_table_name

  # TempFileにファイル内容をコピーしてパスを返す
  @filename = copy_to_tempfile(filename)

  @headers = custom_headers
  @headers ||= File.open(@filename, 'r').first(&:readline).chomp.split("\t")

  validate_headers
end

Instance Attribute Details

#filenameObject (readonly)

Returns the value of attribute filename.



8
9
10
# File 'lib/kandata/tsv_file.rb', line 8

def filename
  @filename
end

#headersObject (readonly)

Returns the value of attribute headers.



8
9
10
# File 'lib/kandata/tsv_file.rb', line 8

def headers
  @headers
end

#table_nameObject (readonly)

Returns the value of attribute table_name.



8
9
10
# File 'lib/kandata/tsv_file.rb', line 8

def table_name
  @table_name
end

Instance Method Details

#duplicated_columnsObject



42
43
44
# File 'lib/kandata/tsv_file.rb', line 42

def duplicated_columns
  @headers.group_by { |value| value }.reject { |_key, value| value.one? }.keys
end

#include_id_column?Boolean

Returns:

  • (Boolean)


54
55
56
# File 'lib/kandata/tsv_file.rb', line 54

def include_id_column?
  @headers.include?('id')
end

#include_reserved_name?Boolean

Returns:

  • (Boolean)


50
51
52
# File 'lib/kandata/tsv_file.rb', line 50

def include_reserved_name?
  RESERVED_COLUMNS.any? { |name| @headers.include?(name) }
end

#invalid_columnsObject



46
47
48
# File 'lib/kandata/tsv_file.rb', line 46

def invalid_columns
  @headers.reject { |value| value.match?(/^[0-9a-zA-Z$_]+$/) }
end

#validate_headersObject



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/kandata/tsv_file.rb', line 30

def validate_headers
  raise "以下のカラムが複数存在しています #{duplicated_columns}" unless duplicated_columns.empty?

  raise "以下のカラム名は使用できません #{invalid_columns}" unless invalid_columns.empty?
  raise "以下のカラム名は使用できません #{RESERVED_COLUMNS}" if include_reserved_name?

  # 現時点では、ミス防止のため、先頭以外にidカラムがあるとエラーとして処理する
  raise '先頭以外にidカラムがあります' if include_id_column? && @headers[0] != 'id'

  true
end

#validate_table_nameObject



25
26
27
28
# File 'lib/kandata/tsv_file.rb', line 25

def validate_table_name
  raise 'テーブル名に使用できないファイル名です' unless @table_name.match?(/^[0-9a-zA-Z$_]+$/)
  true
end