Created
January 28, 2014 11:55
-
-
Save ryaz/8666409 to your computer and use it in GitHub Desktop.
module example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module WizardConcern | |
extend ActiveSupport::Concern | |
included do | |
has_many :step_statuses, dependent: :destroy | |
has_many :steps_completed, through: :step_statuses, source: :step, class_name: 'Step' | |
has_many :wizard_progresses, dependent: :destroy | |
delegate :wizards, to: :organization | |
delegate :steps, to: :organization | |
delegate :rewards, to: :organization | |
after_create :calc_org_wizards_progress! | |
after_destroy :calc_org_wizards_progress! | |
end | |
def progress(wizard) | |
wizard_progresses.where(wizard_id: wizard.id).first.try(:progress) || 0 | |
end | |
def last_step | |
step_statuses.last.try(:step) | |
end | |
def set_step(step) | |
ss = step_statuses.where(step_id: step.id).first_or_initialize | |
ss.completed_at = Time.now | |
ss.save | |
end | |
def get_step(step) | |
step_statuses.where(step_id: step.id).first | |
end | |
def step_completed?(step) | |
steps_completed.include? step | |
end | |
def reward_obtained?(reward) | |
if (ch = reward.wizards.first) | |
progress(ch) >= 100 | |
else | |
ch = wizards.last | |
ch.progress >= ch.goal.to_i | |
end | |
end | |
def wizard_flow? | |
!organization.default? and wizards.any? | |
end | |
def calc_step_statuses! | |
delete_wizards_info | |
calc_step_statuses | |
end | |
def calc_wizards_progresses! | |
wizards.each {|ch| calc_wizard_progress!(ch)} | |
end | |
def calc_wizards_info! | |
if wizard_flow? | |
calc_step_statuses! | |
self.reload | |
calc_wizards_progresses! | |
end | |
calc_org_wizards_progress! | |
end | |
private | |
def update_progress_on_org_change(prev_org) | |
prev_org.wizards.each {|ch| ch.calc_progress!} if prev_org.wizard_flow? | |
calc_wizards_info! | |
end | |
def calc_org_wizards_progress! | |
wizards.each {|ch| ch.calc_progress!} if wizard_flow? | |
end | |
def delete_wizards_info | |
StepStatus.delete_all(user_id: self.id) | |
WizardProgress.delete_all(user_id: self.id) | |
end | |
def calc_step_statuses | |
completed_datums = result_aggregators.map &:datum_name | |
steps.each do |step| | |
set_step(step) if completed_datums.include?(step.action) | |
end | |
end | |
def calc_wizard_progress!(wizard) | |
cp, status_step_ids = wizard_progresses.where(wizard_id: wizard.id).first_or_initialize, step_statuses_step_ids | |
cp.progress = wizard.steps.select {|s| status_step_ids.include?(s.id)}.map(&:percents).sum | |
cp.save | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment