jam-cloud/ruby/lib/jam_ruby/models/country.rb

54 lines
1.8 KiB
Ruby

module JamRuby
class Country < ActiveRecord::Base
self.table_name = 'countries'
def self.get_all()
self.order('countryname asc').all
end
def self.import_from_iso3166(file)
# File iso3166.csv
# Format:
# countrycode,countryname
# what this does is not replace the contents of the table, but rather update the specified rows with the names.
# any rows not specified have the countryname reset to be the same as the countrycode.
self.transaction do
self.connection.execute "update #{self.table_name} set countryname = countrycode"
File.open(file, 'r:ISO-8859-1') do |io|
saved_level = ActiveRecord::Base.logger ? ActiveRecord::Base.logger.level : 0
count = 0
ncols = 2
csv = ::CSV.new(io, {encoding: 'ISO-8859-1', headers: false})
csv.each do |row|
raise "file does not have expected number of columns (#{ncols}): #{row.length}" unless row.length == ncols
countrycode = row[0]
countryname = row[1]
stmt = "UPDATE #{self.table_name} SET countryname = #{MaxMindIsp.quote_value(countryname)} WHERE countrycode = #{MaxMindIsp.quote_value(countrycode)}"
self.connection.execute stmt
count += 1
if ActiveRecord::Base.logger and ActiveRecord::Base.logger.level < Logger::INFO
ActiveRecord::Base.logger.debug "... logging updates to #{self.table_name} suspended ..."
ActiveRecord::Base.logger.level = Logger::INFO
end
end
if ActiveRecord::Base.logger
ActiveRecord::Base.logger.level = saved_level
ActiveRecord::Base.logger.debug "updated #{count} records in #{self.table_name}"
end
end # file
end # transaction
end
end
end