Class: Ip2locationCountry

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(csv) ⇒ Ip2locationCountry

Returns a new instance of Ip2locationCountry.



1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
# 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

Instance Attribute Details

#fieldsObject

Returns the value of attribute fields.



1037
1038
1039
# File 'lib/ip2location_ruby.rb', line 1037

def fields
  @fields
end

#recordsObject

Returns the value of attribute records.



1037
1038
1039
# File 'lib/ip2location_ruby.rb', line 1037

def records
  @records
end

Instance Method Details

#get_country_info(country_code = nil) ⇒ Object



1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
# 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