Sha256: d0346eeb89eac21a3dc9dd095b0a166494167d77d3178ebec090daec7c536d13

Contents?: true

Size: 1.3 KB

Versions: 3

Compression:

Stored size: 1.3 KB

Contents

module GoGamification::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
        ::GoGamification::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

3 entries across 3 versions & 1 rubygems

Version Path
go_gamification-0.0.7 lib/go_gamification/concerns/models/goal.rb
go_gamification-0.0.6 lib/go_gamification/concerns/models/goal.rb
go_gamification-0.0.4 lib/go_gamification/concerns/models/goal.rb