Class: Ekylibre::AnimalsExchanger

Inherits:
ActiveExchanger::Base show all
Defined in:
app/exchangers/ekylibre/animals_exchanger.rb

Instance Attribute Summary

Attributes inherited from ActiveExchanger::Base

#file, #supervisor

Instance Method Summary collapse

Methods inherited from ActiveExchanger::Base

build, check, check_by_default, exchanger_name, export, exporters, find, human_name, import, import!, importers, importers_selection, inherited, #initialize, register_exchanger

Constructor Details

This class inherits a constructor from ActiveExchanger::Base

Instance Method Details

#importObject

Create or updates animals


4
5
6
7
8
9
10
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
44
45
46
47
48
49
50
51
52
# File 'app/exchangers/ekylibre/animals_exchanger.rb', line 4

def import
  rows = CSV.read(file, headers: true).delete_if { |r| r[0].blank? }
  w.count = rows.size

  rows.each do |row|
    r = OpenStruct.new(
      name: row[0],
      nature: row[1].to_sym,
      code: (row[2].blank? ? nil : row[2].to_s),
      place: (row[3].blank? ? nil : row[3].to_s),
      group: (row[4].blank? ? nil : row[4].to_s),
      born_at: (row[5].blank? ? Time.zone.today : row[5]).to_datetime,
      variety: (row[6].blank? ? nil : row[6].to_sym),
      initial_owner: (row[7].blank? ? nil : row[7].to_s),
      indicators: row[8].blank? ? {} : row[8].to_s.strip.split(/[[:space:]]*\;[[:space:]]*/).collect { |i| i.split(/[[:space:]]*\:[[:space:]]*/) }.inject({}) do |h, i|
        h[i.first.strip.downcase.to_sym] = i.second
        h
      end,
      record: nil
    )

    unless animal = Animal.find_by(work_number: r.code)
      animal = Animal.create!(
        name: r.name,
        work_number: r.code,
        identification_number: r.code,
        initial_born_at: r.born_at,
        variant: ProductNatureVariant.import_from_nomenclature(r.nature),
        default_storage: BuildingDivision.find_by(work_number: r.place)
      )
      # create indicators linked to animal
      r.indicators.each do |indicator_name, value|
        next if indicator_name == :population
        animal.read!(indicator_name, value, at: r.born_at, force: true)
      end
      animal.initial_population = animal.population
      animal.variety = r.variety if r.variety
      if owner = Entity.find_by_full_name(r.initial_owner)
        animal.initial_owner = owner
      end
      if r.group && animal_group = AnimalGroup.find_by(work_number: r.group)
        animal.memberships.create!(group: animal_group, started_at: r.born_at, nature: :interior)
      end
      animal.save!
    end

    w.check_point
  end
end