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_xx_region(countrycode, file) # File xx_region.csv # Format: # region,regionname # what this does is not replace the contents of the table, but rather update the specifies rows with the names. # any rows not specified are left alone. the parameter countrycode denote the country of the region (when uppercased) raise "countrycode (#{MaxMindIsp.quote_value(countrycode)}) is missing or invalid (it must be two characters)" unless countrycode and countrycode.length == 2 countrycode = countrycode.upcase self.transaction do self.connection.execute "update #{self.table_name} set regionname = region where countrycode = #{MaxMindIsp.quote_value(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 region = row[0] regionname = row[1] stmt = "UPDATE #{self.table_name} SET regionname = #{MaxMindIsp.quote_value(regionname)} WHERE countrycode = #{MaxMindIsp.quote_value(countrycode)} AND region = #{MaxMindIsp.quote_value(region)}" 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