Sha256: 3a3384bb6cb88d12aea77b5108e9c795b54c51783ba0872523aee9a89ebbccf5

Contents?: true

Size: 1.45 KB

Versions: 1

Compression:

Stored size: 1.45 KB

Contents

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

  included do
    belongs_to :taskable, polymorphic: true
    has_many :scorings

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

    # Determine whether the given subject has completed the task.
    #
    # subject - An ActiveRecord model that can receive scorings.
    def completed_by? subject
      !!scoring_for(subject)
    end

    # Complete the task for the given subject.
    #
    # subject - An ActiveRecord model that can receive scorings.
    def complete_for subject
      if completed_by? subject
        raise Completed, "Task is already completed for #{subject}"
      else
        ::Gamification::Scoring.create! task: self, subjectable: subject
      end
    end

    private

    # Find the Scoring for the given subject.
    #
    # subject - An ActiveRecord model that can receive scorings.
    def scoring_for subject
      scorings.find_by subjectable: subject
    end

    class Completed < StandardError; end
  end

  module ClassMethods
    # Complete all tasks for the given subject.
    #
    # subject - An ActiveRecord model that can receive scorings.
    def complete_for subject
      all.map { |task| task.complete_for subject unless task.completed_by? subject }.compact
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
gamification-0.0.2 lib/gamification/concerns/models/task.rb