Class: ActiveMerge::SimpleService

Inherits:
ActivePatterns::BaseService
  • Object
show all
Includes:
ActiveModel::Validations
Defined in:
lib/active_merge/simple_service.rb

Overview

Service Object responds for merging two ActiveRecord instances as a whole transaction.

All objects linked to the second instance via “has_many” association are re-associated to the first one.

Then the second instance removed. All errors collected in the #errors method.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(first, second) ⇒ SimpleService

Returns a new instance of SimpleService.



18
19
20
21
22
23
24
# File 'lib/active_merge/simple_service.rb', line 18

def initialize(first, second)
  @klass  = first.class
  return unless klass.ancestors.include?(ActiveRecord::Base) &&
    second.is_a?(klass) && first.persisted? && second.persisted?
  @first, @second = first, second
  @links  = find_links
end

Instance Attribute Details

#firstObject (readonly)

Returns the value of attribute first.



25
26
27
# File 'lib/active_merge/simple_service.rb', line 25

def first
  @first
end

#klassObject (readonly)

Returns the value of attribute klass.



25
26
27
# File 'lib/active_merge/simple_service.rb', line 25

def klass
  @klass
end

Returns the value of attribute links.



25
26
27
# File 'lib/active_merge/simple_service.rb', line 25

def links
  @links
end

#secondObject (readonly)

Returns the value of attribute second.



25
26
27
# File 'lib/active_merge/simple_service.rb', line 25

def second
  @second
end

Instance Method Details

#provide(validate: true) ⇒ Object



29
30
31
32
33
34
# File 'lib/active_merge/simple_service.rb', line 29

def provide(validate: true)
  transaction do
    remove_second! validate
    save_links! validate
  end
end