Class: Ip2locationRegion

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(csv) ⇒ Ip2locationRegion

Returns a new instance of Ip2locationRegion.



1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
# File 'lib/ip2location_ruby.rb', line 1103

def initialize(csv)
  if csv == ''
    abort('The CSV file "' + csv + '" is not found.')
  end

  begin
    csvfile = File.open(File.expand_path csv, 'rb')
  rescue
    abort('Error in opening ' + csv + '. No such CSV file in the /your_ip2location_ruby_library_path/rb/ folder.')
  else
  end

  begin
    CSV.parse(csvfile)
  rescue
    abort('Unable to read "' + csv + '".')
  else
    line = 1
    self.records = Hash.new
    CSV.foreach((csvfile)) do |data|
      if line == 1
        if data[1] != 'subdivision_name'
          abort('Invalid region information CSV file.')
        end
      else
        temp_data = Hash.new
        temp_data['code'] = data[2]
        temp_data['name'] = data[1]
        if self.records[data[0]]
          self.records[data[0]].push temp_data
        else
          self.records[data[0]] = [temp_data]
        end
      end
      line = line + 1
    end
  end
end

Instance Attribute Details

#recordsObject

Returns the value of attribute records.



1101
1102
1103
# File 'lib/ip2location_ruby.rb', line 1101

def records
  @records
end

Instance Method Details

#get_region_code(country_code, region_name) ⇒ Object



1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
# File 'lib/ip2location_ruby.rb', line 1142

def get_region_code(country_code, region_name)
  if self.records.empty?
    abort('No record available.')
  end

  if (self.records[country_code]).nil?
    return
  end

  for i in 0..(self.records[country_code].length()-1)
    if region_name.upcase == self.records[country_code][i]["name"].upcase
      return self.records[country_code][i]["code"]
    end
  end
end