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",
  "tag_names",
  "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, publishable_only: false) ⇒ DuplicateElement

Returns a new instance of DuplicateElement.



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

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

Instance Attribute Details

#publishable_only ⇒ Object (readonly)

Returns the value of attribute publishable_only.



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

def publishable_only
  @publishable_only
end

#repository ⇒ Object (readonly)

Returns the value of attribute repository.



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

def repository
  @repository
end

#source_element ⇒ Object (readonly)

Returns the value of attribute source_element.



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

def source_element
  @source_element
end

Instance Method Details

#call(differences = {}) ⇒ Object



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 25

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

  new_element = Element.new(attributes)
  # Only assign tags when the source has any, so copying untagged elements
  # (the common case) does not trigger gutentag's tag reconciliation.
  new_element.tag_list = source_element.tag_list if source_element.tag_list.present?
  new_element.ingredients = source_element.ingredients.map(&:dup)
  new_element.save!

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

  new_element
end