Module: Course::LevelsConcern

Extended by:
ActiveSupport::Concern
Defined in:
app/models/concerns/course/levels_concern.rb

Instance Method Summary collapse

Instance Method Details

#default_level?Boolean

Test if the course has a default level.

Returns:

  • (Boolean)

    True if there is a default level, otherwise false.


25
26
27
# File 'app/models/concerns/course/levels_concern.rb', line 25

def default_level?
  any?(&:default_level?)
end

#level_for(experience_points) ⇒ Course::Level

Returns the Course::Level object corresponding to the experience points provided. To use ruby to obtain the required level, ensure that course.levels is already loaded. Otherwise, an SQL call is fired for each method call.

If experience_points <= 0, the level is assumed to be the default level (the 0th level) with 0 experience_points threshold.

Parameters:

  • experience_points (Integer)

    Number of Experience Points

Returns:


14
15
16
17
18
19
20
21
# File 'app/models/concerns/course/levels_concern.rb', line 14

def level_for(experience_points)
  return first if experience_points < 0
  if loaded?
    reverse.find { |level| level.experience_points_threshold <= experience_points }
  else
    reverse_order.find_by('experience_points_threshold <= ?', experience_points)
  end
end

#mass_update_levels(new_thresholds) ⇒ Array<Course::Level>

Delete and create Course::Level objects so they match new given thresholds.

Parameters:

  • new_thresholds (Array<Integer>)

    Array of the new experience point thresholds.

Returns:

  • (Array<Course::Level>)

    Level objects with the new thresholds.


33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'app/models/concerns/course/levels_concern.rb', line 33

def mass_update_levels(new_thresholds)
  # Ensure that the default level is still present in the new set of thresholds.
  new_thresholds << 0 unless new_thresholds.include?(Course::Level::DEFAULT_THRESHOLD)

  Course::Level.transaction do
    # Delete Course::Level objects which are not in the new set of thresholds.
    delete(select { |level| !new_thresholds.include?(level.experience_points_threshold) })

    new_thresholds.map do |threshold|
      find_or_create_by(experience_points_threshold: threshold)
    end
  end
end