Class: IPLibrary::Data

Inherits:
Object
  • Object
show all
Defined in:
lib/ip_library/data.rb

Constant Summary collapse

TITLES =
%w(start_ip end_ip province city district area_name_py start_ip1 end_ip1)
MUNICIPALITIES =
%w(北京 上海 天津 重庆)
DISTRICT_REGEXP =
/(自治县|自治旗|特区|林区|县|区|旗)$/
CITY_REGEXP =
/(自治州|地区|市|州|盟)$/
PROVINCE_REGEXP =
/(省|自治区|特别行政区)$/

Class Method Summary collapse

Class Method Details

.generate_custom_ip_library(areas, outfile_path = nil, infile_path = nil) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/ip_library/data.rb', line 36

def generate_custom_ip_library(areas, outfile_path = nil, infile_path = nil)
  infile_path  ||= Configuration.file_path
  outfile_path ||= File.join(Rails.root, 'doc', 'custom_ip_libraries.txt')
  ip_city_ids = get_ip_city_ids(areas)

  writer = []
  File.open(infile_path, 'r') do |file|
    file.each_line do |line|
      if (cols = line.split(',')).size == 5 && ip_city_ids[cols[2]].present? && (city_id = (ip_city_ids[cols[2]][cols[3]] || ip_city_ids[cols[2]][cols[4]])).present?
        writer << "#{cols[0]},#{cols[1]},#{city_id}\n"
      elsif cols.size != 5
        writer << cols.join(',')
      end
    end
  end

  puts "正在生成#{outfile_path}"
  File.open(outfile_path, 'w') do |file|
    writer.each do |line|
      file.write line
    end
  end
  puts '生成完毕'
end

.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