class Csv::Query::CLI::InMemoryAR
Attributes
file_path[R]
json[R]
sql[R]
Public Class Methods
new(file_path, json, sql)
click to toggle source
# File lib/csv/query.rb, line 64 def initialize(file_path, json, sql) @sql = sql @json = json @file_path = file_path migration(csv_headers) end
Public Instance Methods
csv()
click to toggle source
# File lib/csv/query.rb, line 47 def csv case 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) when "ISO-8859-1" CSV.read(file_path, encoding: "ISO8859-1:UTF-8", headers: true, header_converters: header_converter) end end
csv_headers()
click to toggle source
# File lib/csv/query.rb, line 58 def csv_headers csv.headers end
encoding()
click to toggle source
# File lib/csv/query.rb, line 41 def encoding contents = File.read(file_path) detection = contents.detect_encoding detection[:encoding] end
header_converter()
click to toggle source
`LP(iphone)`みたいに 半角カッコ内にアルファベットだと Rubyのsyntax的にsetterと勘違いされるので対策
# File lib/csv/query.rb, line 35 def header_converter lambda do |h| h.gsub('(','(').gsub(')', ')') end end
json_format?()
click to toggle source
# File lib/csv/query.rb, line 86 def json_format? json end
migration(csv_headers)
click to toggle source
# File lib/csv/query.rb, line 72 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
records()
click to toggle source
# File lib/csv/query.rb, line 98 def records if sql.present? InMemoryAR::Record.find_by_sql(sql) else InMemoryAR::Record.all end end
render(records)
click to toggle source
# File lib/csv/query.rb, line 106 def render records if json_format? puts Array.wrap(records).map { |e| e.to_h }.to_json else rows = Array.wrap(records).map { |e| e.to_h.values } puts Terminal::Table.new :headings => csv_headers, :rows => rows end end
run!()
click to toggle source
# File lib/csv/query.rb, line 90 def run! csv.each do |row| Record.create!(row.to_h) end render(records) end