Class: ResourceUpdater

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

Overview

Service object: resource updater.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(search, params = {}) ⇒ ResourceUpdater

Returns a new instance of ResourceUpdater.



6
7
8
9
10
11
12
# File 'app/services/resource_updater.rb', line 6

def initialize(search, params = {})
  raise "Cannot initialize Resource updater without search" unless search.is_a? Search

  @search = search
  @resource_params = params
  reset
end

Instance Attribute Details

#errorsObject (readonly)

Returns the value of attribute errors.



4
5
6
# File 'app/services/resource_updater.rb', line 4

def errors
  @errors
end

#searchObject (readonly)

Returns the value of attribute search.



4
5
6
# File 'app/services/resource_updater.rb', line 4

def search
  @search
end

Instance Method Details

#add_errors(new_errors) ⇒ Object



54
55
56
57
# File 'app/services/resource_updater.rb', line 54

def add_errors(new_errors)
  @errors ||= []
  @errors += [new_errors].flatten
end

#perform(order_clause = nil) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'app/services/resource_updater.rb', line 14

def perform(order_clause = nil)
  reset
  results = @search.pinned_query
  results = results.order(order_clause) if order_clause
  results.select(&:resource).each do |sr|
    resource = sr.resource
    resource.assign_attributes @resource_params if @resource_params.present?
    if block_given?
      block_results = yield(resource)
      if block_results.is_a? Hash
        msg = block_results[:ok]
        if msg
          true
        elsif block_results[:error].present?
          @errors << block_results[:error]
        end
      end
    end
    resource.save
    success = record_resource_errors(resource)
    next unless success

    @updated += 1
    @successes << resource
    # remove from search results
    sr.delete
  end
  status
end

#record_resource_errors(resource) ⇒ Object

returns true if record is clean



45
46
47
48
49
50
51
52
# File 'app/services/resource_updater.rb', line 45

def record_resource_errors(resource)
  if resource.errors.present?
    add_errors "#{resource.class.name} id #{resource.id} errors: \n\t#{resource.errors_to_s}"
    false
  else
    true
  end
end

#statusObject



63
64
65
66
67
68
69
# File 'app/services/resource_updater.rb', line 63

def status
  res = {}
  res[:status] = @errors.empty? ? :ok : :error
  res[:message] = "#{@updated} records updated. #{@errors.join('.')}"
  res[:successes] = @successes
  res
end

#updated_countObject



59
60
61
# File 'app/services/resource_updater.rb', line 59

def updated_count
  @updated
end