Sha256: 5d68480814442fb50f6cde04360bc956ec0d6b9d53aab8cfc6ba0308592d211f

Contents?: true

Size: 1.29 KB

Versions: 4

Compression:

Stored size: 1.29 KB

Contents

module Gamification::Concerns::Models::Goal
  extend ActiveSupport::Concern

  included do
    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
        ::Gamification::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

    class Completed < StandardError; end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
gamification-1.0.3 lib/gamification/concerns/models/goal.rb
gamification-1.0.2 lib/gamification/concerns/models/goal.rb
gamification-1.0.1 lib/gamification/concerns/models/goal.rb
gamification-1.0.0 lib/gamification/concerns/models/goal.rb