Sha256: 0bde949a702351900327662260d6493573442ebe76f198437fc1642c0f7237f4

Contents?: true

Size: 1.2 KB

Versions: 8

Compression:

Stored size: 1.2 KB

Contents

module Gamification
  class Goal < ApplicationRecord
    belongs_to :rewarding, polymorphic: true
    has_one :medal, dependent: :destroy
    has_many :rewards, dependent: :destroy

    accepts_nested_attributes_for :medal, allow_destroy: true, reject_if: :all_blank

    # TODO: These should be SQL. But that's hard.
    scope :completed_by,  ->(subject) { all.select { |goal| goal.completed_by? subject }}
    scope :incomplete_by, ->(subject) { all.reject { |goal| goal.completed_by? subject }}

    # Determine whether the given subject has completed the goal.
    #
    # subject - An ActiveRecord model that can receive rewards.
    def completed_by? subject
      !!reward_for(subject)
    end

    # Complete the goal for the given subject.
    #
    # subject - An ActiveRecord model that can receive rewards.
    def complete_for subject
      if completed_by? subject
        raise Completed, "#{self} is already completed for #{subject}"
      else
        Reward.create! goal: self, rewardable: subject
      end
    end

    private

    # Find the Reward for the given subject.
    #
    # subject - A rewardable model.
    def reward_for rewardable
      rewards.find_by rewardable: rewardable
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
go_gamification-0.0.20 app/models/gamification/goal.rb
go_gamification-0.0.19 app/models/gamification/goal.rb
go_gamification-0.0.18 app/models/gamification/goal.rb
go_gamification-0.0.17 app/models/gamification/goal.rb
go_gamification-0.0.16 app/models/gamification/goal.rb
go_gamification-0.0.15 app/models/gamification/goal.rb
go_gamification-0.0.14 app/models/gamification/goal.rb
go_gamification-0.0.13 app/models/gamification/goal.rb