Method: IPLibrary::Data.generate_txt

Defined in:
lib/ip_library/data.rb

.generate_txt(infile_path, outfile_path = nil) ⇒ Object

Raises:

  • (ArgumentError)


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/ip_library/data.rb', line 14

def generate_txt(infile_path, outfile_path = nil)
  outfile_path ||= "#{Rails.root}/doc/#{Time.now.strftime('%y%m%d%H%M%S')}_ip_libraries.txt"
  raise ArgumentError, '请出入正确的文件路径!' unless File.file?(infile_path) || File.extname(infile_path) != '.txt'

  puts '正在生成txt文件'
  File.open(outfile_path, 'w') do |file|
    ip_cities = load_csv(infile_path).sort_by { |row| row[TITLES.index('start_ip')].to_i }
    ip_cities = ip_cities.group_by { |row| row[TITLES.index('start_ip1')].split('.').first }
    length    = ip_cities.keys.size
    index     = 0
    ip_cities.each do |key, value|
      index += 1
      file.write("#{key}\n")
      value.each do |v|
        file.write("#{v[0..4].join(',')}\n")
      end
      file.write("#{Configuration.separator}") if length != index
    end
  end
  puts "已经生成txt文件:#{outfile_path}"
end