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

60 lines
2.1 KiB
Ruby

module JamRuby
class Region < ActiveRecord::Base
self.table_name = 'regions'
def self.get_all(country)
self.where(countrycode: country).order('regionname asc').all
end
def self.import_from_region_codes(file)
# File region_codes.csv
# Format:
# countrycode,region,regionname
# what this does is replace the contents of the table with the new data.
self.transaction do
self.connection.execute "delete from #{self.table_name}"
File.open(file, 'r:ISO-8859-1') do |io|
saved_level = ActiveRecord::Base.logger ? ActiveRecord::Base.logger.level : -1
count = 0
errors = 0
ncols = 3
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]
region = row[1]
regionname = row[2]
if countrycode.length == 2 and region.length == 2 and regionname.length >= 2 and regionname.length <= 64
stmt = "INSERT INTO #{self.table_name} (countrycode, region, regionname) VALUES (#{self.connection.quote(countrycode)}, #{self.connection.quote(region)}, #{self.connection.quote(regionname)})"
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
else
ActiveRecord::Base.logger.warn("bogus region_codes record '#{countrycode}', '#{region}', '#{regionname}'") if ActiveRecord::Base.logger
errors += 1
end
end
if ActiveRecord::Base.logger
ActiveRecord::Base.logger.level = saved_level
ActiveRecord::Base.logger.debug "inserted #{count} records into #{self.table_name}, #{errors} errors"
end
end # file
end # transaction
end
end
end