Class: ResourceUpdater

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of ResourceUpdater.



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

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

Instance Attribute Details

#errorsObject (readonly)

Returns the value of attribute errors.



2
3
4
# File 'app/services/resource_updater.rb', line 2

def errors
  @errors
end

#searchObject (readonly)

Returns the value of attribute search.



2
3
4
# File 'app/services/resource_updater.rb', line 2

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



11
12
13
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
43
# File 'app/services/resource_updater.rb', line 11

def perform(order_clause = nil)
  reset
  results = @search.pinned_query
  results = results.order(order_clause) if order_clause
  results.select(&:resource).each do |sr|
    success = true
    resource = sr.resource
    if @resource_params.present?
      resource.assign_attributes @resource_params
    end
    if block_given?
      block_results = yield(resource)
      if block_results.is_a? Hash
        msg = block_results[:ok]
        if msg
          success = true
        else
          success = false
          @errors << block_results[:error] if block_results[:error].present?
        end
      end
    end
    resource.save
    success = record_resource_errors(resource)
    if success
      @updated = @updated + 1
      @successes << resource
      #remove from search results
      sr.delete
    end
  end
  return 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) #returns true if record is clean
  if resource.errors.present?
    add_errors "#{resource.class.name} id #{resource.id} errors: \n\t#{resource.errors_to_s}"
    return false
  else
    return 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