Skip to content

Instantly share code, notes, and snippets.

@maciejsmolinski
Created August 3, 2011 11:41
Show Gist options
  • Save maciejsmolinski/1122438 to your computer and use it in GitHub Desktop.
Save maciejsmolinski/1122438 to your computer and use it in GitHub Desktop.
class Battle < ActiveRecord::Base
include Workflow
default_value_for :state, "pending"
after_save :update_users_states
workflow_column :state
workflow do
state :pending do # valid for 2 weeks
event :open, :transitions_to => :awaiting_videos
event :close_no_opponent, :transitions_to => :closed_no_opponent
end
state :awaiting_videos do # valid for 5 days
event :start, :transitions_to => :awaiting_votes
event :close_no_video, :transitions_to => :closed_no_video
event :close_no_videos, :transitions_to => :closed_no_videos
end
state :awaiting_votes do # valid for selected deadline
event :close_no_votes, :transitions_to => :closed_no_votes
event :close_ex_equo, :transitions_to => :closed_ex_equo
event :close_more_votes, :transitions_to => :closed_more_votes
event :close, :transitions_to => :closed
end
state :closed_no_opponent
state :closed_no_video
state :closed_no_videos
state :closed_no_votes
state :closed_ex_equo
state :closed_more_votes
state :closed
# state :rejected
end
scope :awaiting_videos, lambda { # MY BATTLES section
where("state = ?", "awaiting_videos")
}
scope :awaiting_votes, lambda { # CURRENT BATTLES section
where("state = ?", "awaiting_votes")
}
scope :finished, lambda { # FINISHED BATTLES section
where("state in (?)", ["closed_no_votes", "closed_ex_equo", "closed_more_votes", "closed"])
}
scope :pending, lambda { # JOIN section && computing states purposes
where("state = ?", "pending")
}
scope :closed_dq, lambda { # CLOSED BATTLES section
where("state IN(?)", ["closed_no_video", "closed_no_videos"])
}
scope :closed_no_opponent, lambda { # NOT BATTLED section
where("state = ?", "closed_no_opponent")
}
# CRON PURPOSES:
scope :created_before_2_weeks, lambda { ## computing states purposes
where("created_at <= ?", 14.days.ago.beginning_of_day)
}
scope :awaiting_videos_dq, lambda { ## computing states purposes
awaiting_videos.where("updated_at < ?", 5.days.ago.beginning_of_day)
}
scope :awaiting_votes_to_close, lambda { ## computing states purposes
awaiting_votes.where("finish_date < ?", Time.now.utc.to_date)
}
def deadline
return (created_at + 13.days).end_of_day if pending?
return (updated_at + 4.days).end_of_day if awaiting_videos?
return (finish_date - 1.day).end_of_day if awaiting_votes?
end
def finished?
return ["closed_no_votes", "closed_ex_equo", "closed_more_votes", "closed"].include? state
end
def closed?
return ["closed_no_opponent", "closed_no_video", "closed_no_videos"].include? state
end
private
def get_battle_computation
BattleComputation.new(self)
end
def update_users_states
get_battle_computation.update_users_states
end
...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment