scinote-web/app/services/repository_actions/duplicate_rows.rb

57 lines
1.4 KiB
Ruby
Raw Normal View History

# frozen_string_literal: true
2018-04-13 17:47:33 +08:00
require 'repository_actions/duplicate_cell'
module RepositoryActions
2018-04-13 17:47:33 +08:00
class DuplicateRows
attr_reader :number_of_duplicated_items
2018-04-13 17:47:33 +08:00
def initialize(user, repository, rows_ids = [])
@user = user
@repository = repository
2018-04-13 17:47:33 +08:00
@rows_to_duplicate = sanitize_rows_to_duplicate(rows_ids)
@number_of_duplicated_items = 0
end
def call
2018-04-13 17:47:33 +08:00
@rows_to_duplicate.each do |row_id|
duplicate_row(row_id)
end
end
private
2018-04-13 17:47:33 +08:00
def sanitize_rows_to_duplicate(rows_ids)
process_ids = rows_ids.map(&:to_i).uniq
@repository.repository_rows.where(id: process_ids).pluck(:id)
end
2018-04-13 17:47:33 +08:00
def duplicate_row(id)
row = RepositoryRow.find_by_id(id)
new_row = RepositoryRow.new(
row.attributes.merge(new_row_attributes(row.name))
)
if new_row.save
@number_of_duplicated_items += 1
row.repository_cells.each do |cell|
2018-04-13 17:47:33 +08:00
duplicate_repository_cell(cell, new_row)
end
end
end
def new_row_attributes(name)
timestamp = DateTime.now
{ id: nil,
name: "#{name} (1)",
created_at: timestamp,
updated_at: timestamp }
end
2018-04-13 17:47:33 +08:00
def duplicate_repository_cell(cell, new_row)
RepositoryActions::DuplicateCell.new(
2018-04-19 19:04:16 +08:00
cell, new_row, @user, @repository.team
2018-04-13 17:47:33 +08:00
).call
end
end
end