This repository has been archived by the owner on Apr 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
contest.rb
78 lines (61 loc) · 1.89 KB
/
contest.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
require 'mongoid'
require 'mongoid/slug'
require 'gravtastic'
require 'state'
require 'time_from_date_field'
require 'mongoid_extensions'
class Contest
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Slug
field :name, :type => String
field :tagline, :type => String
field :description, :type => String
field :starting_on, :type => Date
field :voting_on, :type => Date
field :closing_on, :type => Date
slug :name
include TimeFromDateField
include State
validates :user, :name, :description, :starting_on, :tagline, :presence => true
validates :tagline, :length => { :minimum => 50 }
before_create :set_voting_and_closing_dates
embeds_many :entries
belongs_to :user
def self.not_open
Contest.all.reject { |contest| contest.open? }
end
def self.active
scoped.order_by([:starting_on, :desc]).reject { |c| c.pending? }
end
def self.by_slug(slug)
contest = first(:conditions => {:slug => slug})
contest || raise(Mongoid::Errors::DocumentNotFound.new(Contest, slug))
end
def if_open
open? ? self : not_found
end
def set_voting_and_closing_dates
self.voting_on = starting_on + 1.week if self.voting_on.blank?
self.closing_on = voting_on + 1.week if self.closing_on.blank?
end
def add_participations_to_contestants!
entries.order_by([:score, :desc]).each_with_index do |entry, index|
entry.user.participations << {
'contest_id' => id,
'contest_name' => name,
'contest_slug' => slug,
'points' => (entries.length.max(10) - index).min(1) * 10,
'score' => entry.read_attribute(:score),
'position' => index + 1
} unless entry.user.participation_for? self
entry.user.save!
end
end
def has_entry_from?(user)
entries.where(:user_id => user.id).any?
end
def voted_entries(user)
user ? entries.select { |e| e.votes_from?(user) } : []
end
end