Class: Alchemy::DuplicateElement

Inherits:
Object
  • Object
show all
Defined in:
app/services/alchemy/duplicate_element.rb

Constant Summary collapse

SKIPPED_ATTRIBUTES_ON_COPY =
[
  "cached_tag_list",
  "created_at",
  "creator_id",
  "position",
  "id",
  "folded",
  "updated_at",
  "updater_id",
].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source_element, repository: source_element.page_version.element_repository) ⇒ DuplicateElement

Returns a new instance of DuplicateElement.



18
19
20
21
# File 'app/services/alchemy/duplicate_element.rb', line 18

def initialize(source_element, repository: source_element.page_version.element_repository)
  @source_element = source_element
  @repository = repository
end

Instance Attribute Details

#repositoryObject (readonly)

Returns the value of attribute repository.



16
17
18
# File 'app/services/alchemy/duplicate_element.rb', line 16

def repository
  @repository
end

#source_elementObject (readonly)

Returns the value of attribute source_element.



16
17
18
# File 'app/services/alchemy/duplicate_element.rb', line 16

def source_element
  @source_element
end

Instance Method Details

#call(differences = {}) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'app/services/alchemy/duplicate_element.rb', line 23

def call(differences = {})
  attributes = source_element.attributes.with_indifferent_access
    .except(*SKIPPED_ATTRIBUTES_ON_COPY)
    .merge(differences)
    .merge(
      autogenerate_contents: false,
      autogenerate_ingredients: false,
      autogenerate_nested_elements: false,
      tags: source_element.tags,
    )

  new_element = Element.new(attributes)
  new_element.ingredients = source_element.ingredients.map(&:dup)
  new_element.save!

  source_element.contents.map do |content|
    Content.copy(content, element: new_element)
  end

  nested_elements = repository.children_of(source_element)
  Element.acts_as_list_no_update do
    nested_elements.each.with_index(1) do |nested_element, position|
      self.class.new(nested_element, repository: repository).call(
        parent_element: new_element,
        page_version: new_element.page_version,
        position: position
      )
    end
  end

  new_element
end