class Ip2locationCountry

Attributes

fields[RW]
records[RW]

Public Class Methods

new(csv) click to toggle source
# File lib/ip2location_ruby.rb, line 1039
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[0] != 'country_code'
          abort('Invalid country information CSV file.')
        end
        self.fields = data
      else
        self.records[data[0]] = data
      end
      line = line + 1
    end
  end
end

Public Instance Methods

get_country_info(country_code = nil) click to toggle source
# File lib/ip2location_ruby.rb, line 1072
def get_country_info(country_code = nil)
  if self.records.empty?
    abort('No record available.')
  end

  if country_code
    if (self.records[country_code]).nil?
      return []
    end
    results = Hash.new
    for i in 0..(self.fields.length()-1)
      results[self.fields[i]] = self.records[country_code][i]
    end
    return results
  end

  results = []
  self.records.each do |key, value|
    data = Hash.new
    for i in 0..(self.fields.length()-1)
      data[self.fields[i]] = self.records[key][i]
    end
    results = results.append(data)
  end
  return results
end