Class: Course::Duplication::ObjectDuplicationService

Inherits:
BaseService
  • Object
show all
Defined in:
app/services/course/duplication/object_duplication_service.rb

Overview

Service to provide duplication of objects from source_course, to destination_course.

Constant Summary collapse

DEFAULT_OBJECT_DUPLICATION_OPTIONS =
{ mode: :object, unpublish_all: true, current_user: User.system }.freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.duplicate_objects(source_course, destination_course, objects, options = {}) ⇒ Object|Array

Constructor for the object duplication service.

Parameters:

  • source_course (Course)

    Course to duplicate from.

  • destination_course (Course)

    Course to duplicate to.

  • objects (Object|Array)

    The object(s) to duplicate.

  • options (Hash) (defaults to: {})

    The options to be sent to the Duplicator object.

Options Hash (options):

  • :current_user (User) — default: +User.system+

    The user triggering the duplication.

Returns:

  • (Object|Array)

    The duplicated object(s).


14
15
16
17
18
19
20
21
# File 'app/services/course/duplication/object_duplication_service.rb', line 14

def duplicate_objects(source_course, destination_course, objects, options = {})
  options[:time_shift] = time_shift(source_course, destination_course)
  options[:source_course] = source_course
  options[:destination_course] = destination_course
  options.reverse_merge!(DEFAULT_OBJECT_DUPLICATION_OPTIONS)
  service = new(options)
  service.duplicate_objects(objects)
end

.time_shift(source_course, destination_course) ⇒ Float

Calculates the time difference between the +start_at+ of the current and target course.

Parameters:

Returns:

  • (Float)

    Time difference between the +start_at+ of both courses.


28
29
30
31
# File 'app/services/course/duplication/object_duplication_service.rb', line 28

def time_shift(source_course, destination_course)
  shift = destination_course.start_at - source_course.start_at
  shift >= 0 ? shift : 0
end

Instance Method Details

#duplicate_objects(objects) ⇒ Object, Array

Duplicate the objects with the duplicator.

Parameters:

  • objects (Object|Array)

    An object or an array of objects to duplicate.

Returns:

  • (Object)

    The duplicated object, if objects is a single object.

  • (Array)

    Array of duplicated objects, if objects is an array.


42
43
44
45
46
47
48
49
50
51
52
# File 'app/services/course/duplication/object_duplication_service.rb', line 42

def duplicate_objects(objects)
  # TODO: Email the user when the duplication is complete.
  Course.transaction do
    duplicated = duplicator.duplicate(objects)
    before_save(objects, duplicated)
    save_success = duplicated.respond_to?(:save) ? duplicated.save : duplicated.all?(&:save)
    after_save_success = save_success && after_save(objects, duplicated)
    raise ActiveRecord::Rollback unless after_save_success
    duplicated
  end
end