Class: Csv::Query::InMemoryAR

Inherits:
Object
  • Object
show all
Defined in:
lib/csv/query.rb

Defined Under Namespace

Classes: Record

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_path) ⇒ InMemoryAR

Returns a new instance of InMemoryAR.



54
55
56
57
58
# File 'lib/csv/query.rb', line 54

def initialize file_path
  @file_path = file_path

  migration(csv_headers)
end

Instance Attribute Details

#file_pathObject (readonly)

Returns the value of attribute file_path.



52
53
54
# File 'lib/csv/query.rb', line 52

def file_path
  @file_path
end

Instance Method Details

#csvObject



37
38
39
40
41
42
43
44
45
46
# File 'lib/csv/query.rb', line 37

def csv
  contents = File.read(file_path)
  detection = contents.detect_encoding
  case detection[:encoding]
  when "Shift_JIS"
    CSV.read(file_path, encoding: "SJIS:UTF-8", headers: true, header_converters: header_converter)
  when "UTF-8"
    CSV.read(file_path, encoding: "UTF-8:UTF-8", headers: true, header_converters: header_converter)
  end
end

#csv_headersObject



48
49
50
# File 'lib/csv/query.rb', line 48

def csv_headers
  csv.headers
end

#header_converterObject

‘LP(iphone)`みたいに半角カッコ内にアルファベットだとRubyのsyntax的にsetterと勘違いされるので対策



31
32
33
34
35
# File 'lib/csv/query.rb', line 31

def header_converter
  lambda do |h|
    h.gsub('(','(').gsub(')', ')')
  end
end

#migration(csv_headers) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/csv/query.rb', line 60

def migration csv_headers
  ActiveRecord::Migration.verbose = false

  ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")

  ActiveRecord::Schema.define(:version => 1) do
    create_table :records do |t|
      csv_headers.map do |column_name|
        t.text column_name.to_sym
      end
    end
  end
end

#run!Object



74
75
76
77
78
79
# File 'lib/csv/query.rb', line 74

def run!
  csv.each do |row|
    Record.create!(row.to_h)
  end
  pp yield
end