box-o-sand/map-mash/app/models/map.rb
Dan Buch d834b81003 Add 'map-mash/' from commit '7f16409d1257e7471fef35c18bcdf32856b908e3'
git-subtree-dir: map-mash
git-subtree-mainline: eacc351b17
git-subtree-split: 7f16409d12
2013-01-09 23:59:47 -05:00

68 lines
1.7 KiB
Ruby

require 'fastercsv'
class Map < ActiveRecord::Base
def self.from_city_name(city_name)
self.find_or_initialize_by_name(city_name).save!
end
def self.pair
second = nil
max_tries = self.count
tries = 0
while second.nil? && tries < max_tries
first = self.all(:order => 'RANDOM()', :limit => 1).first
second = self.all(:order => 'RANDOM()', :limit => 1,
:conditions => [%{
(
points >= :first_points
AND id <> :first_id
) OR (
id NOT IN (
SELECT map_a_id
FROM mashes
WHERE map_b_id = :first_id
)
AND id NOT IN (
SELECT map_b_id
FROM mashes
WHERE map_a_id = :first_id
)
)}, {
:first_id => first.id,
:first_points => first.points
}
]
).first
tries += 1
end
if second.nil?
logger.error('OH CRAP thar be no more pairings for ye olde mashes')
[first, first]
else
[first, second]
end
end
def self.import(csv_filename)
FasterCSV.parse(open(csv_filename), :headers => true,
:header_converters => [:downcase, :symbol]).each do |row|
map = self.find_or_initialize_by_name("#{row[:city]}, #{row[:region]}")
map.save
if block_given?
yield map
end
end
end
def self.mashes
Mash.all(:conditions => ['map_a = :id OR map_b = :id', {:id => self.id}])
end
def rounds
Mash.count(:conditions => ['map_a = :id OR map_b = :id', {:id => self.id}])
end
end