module Names::Nameable

See Name

Public Class Methods

included(base) click to toggle source
# File app/models/names/nameable.rb, line 4
def self.included(base)
  base.before_save :add_name
  base.has_many :names, :order => "year", :as => :nameable
end

Public Instance Methods

add_name() click to toggle source

Remember names from previous years. Keeps the correct name on old results without creating additional teams. This is a bit naive

# File app/models/names/nameable.rb, line 29
def add_name
  last_year = Time.zone.today.year - 1
  if name_was.present? && results_before_this_year? && self.names.none? { |name| name.year == last_year }
    name = names.build(:name => name_was, :year => last_year)
    if self.respond_to?(:first_name)
      name.first_name = first_name_was
    end
    if self.respond_to?(:last_name)
      name.last_name = last_name_was
    end
    name.save!
  end
end
name(date_or_year = nil) click to toggle source
# File app/models/names/nameable.rb, line 9
def name(date_or_year = nil)
  name_record_for_year(parse_year(date_or_year)).try(:name) || read_attribute(:name)
end
name_record_for_year(year) click to toggle source

Returns Name record, not String

# File app/models/names/nameable.rb, line 14
def name_record_for_year(year)
  return nil if year.blank? || year >= Time.zone.today.year || names.none?
  
  # Assume names always sorted
  if year <= names.first.year
    return names.first
  elsif year >= names.last.year
    return names.last
  end
      
  names.detect { |n| n.year == year }
end
results_before_this_year?() click to toggle source
# File app/models/names/nameable.rb, line 43
def results_before_this_year?
  # Exists? doesn't support joins
  count = self.class.count_by_sql([%Q{
    select results.id from #{self.class.table_name}, results, races, events 
    where #{self.class.table_name}.id = ? and #{self.class.table_name}.id = results.#{self.class.name.downcase}_id 
      and results.race_id = races.id
      and races.event_id = events.id and events.date < ? limit 1
  }, id, Time.zone.today.beginning_of_year])
  count > 0
end