Class: Ekylibre::ActivitiesExchanger

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

Overview

Permits to import activities from a CSV file with 3 columns:

- Name
- Family (from nomenclature ActivityFamily)
- Cultivation variety (from nomenclature Variety)

Instance Attribute Summary

Attributes inherited from ActiveExchanger::Base

#file, #supervisor

Instance Method Summary collapse

Methods inherited from ActiveExchanger::Base

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

Constructor Details

This class inherits a constructor from ActiveExchanger::Base

Instance Method Details

#checkObject


7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'app/exchangers/ekylibre/activities_exchanger.rb', line 7

def check
  valid = true
  rows = CSV.read(file, headers: true).delete_if { |r| r[0].blank? }
  w.count = rows.size
  rows.each do |row|
    r = {
      name: row[0].to_s,
      family: (row[1].blank? ? nil : row[1].to_s),
      variety: (row[2].blank? ? nil : row[2].to_sym)
    }.to_struct
    valid = false unless Nomen::ActivityFamily.find(r.family)
    valid = false unless Nomen::Variety.find(r.variety)
    w.check_point
  end
  valid
end

#importObject

Create or updates activities


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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'app/exchangers/ekylibre/activities_exchanger.rb', line 25

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

  rows.each do |row|
    r = {
      name: row[0].to_s,
      family: (row[1].blank? ? nil : row[1].to_s),
      variety: (row[2].blank? ? nil : row[2].to_s)
    }.to_struct

    family = Nomen::ActivityFamily.find(r.family)

    attributes = {
      name: r.name,
      family: r.family,
      cultivation_variety: r.variety,
      with_cultivation: true,
      production_cycle: :annual,
      nature: :main
    }
    if family <= :plant_farming
      attributes.update(
        family: :plant_farming,
        cultivation_variety: r.variety,
        support_variety: :cultivable_zone,
        with_supports: true,
        size_indicator: 'net_surface_area',
        size_unit: 'hectare'
      )
    elsif family <= :animal_farming
      attributes.update(
        family: :animal_farming,
        cultivation_variety: r.variety,
        support_variety: :animal_group,
        with_supports: true,
        size_indicator: 'members_population'
      )
    end
    activity = Activity.find_or_initialize_by(attributes.slice(:name, :family, :cultivation_variety))
    activity.attributes = attributes
    activity.save!
    w.check_point
  end
end