Class: MoyskladIntegration::Entity

Inherits:
Object
  • Object
show all
Defined in:
lib/moysklad_integration/entity.rb

Instance Method Summary collapse

Constructor Details

#initialize(params) ⇒ Entity

Returns a new instance of Entity.



5
6
7
8
9
10
11
12
13
# File 'lib/moysklad_integration/entity.rb', line 5

def initialize(params)
  params.each do |key, val|
    next if val.blank?

    self.class.__send__(:define_method, key, -> { instance_variable_get("@#{key}") })
    self.class.__send__(:define_method, "#{key}=", ->(val) { instance_variable_set("@#{key}", val) })
    __send__("#{key}=", val)
  end
end

Instance Method Details

#add_positions(positions_params) ⇒ Object



30
31
32
# File 'lib/moysklad_integration/entity.rb', line 30

def add_positions(positions_params)
  service.create_positions(self, positions_params)
end


26
27
28
# File 'lib/moysklad_integration/entity.rb', line 26

def meta_link
  { meta: meta }
end

#update(params) ⇒ Object



15
16
17
18
19
20
21
22
23
24
# File 'lib/moysklad_integration/entity.rb', line 15

def update(params)
  params.each do |key, val|
    next if val.blank? || instance_variables.include?(:"@#{key}")

    self.class.__send__(:define_method, key, -> { instance_variable_get("@#{key}") })
    self.class.__send__(:define_method, "#{key}=", ->(val) { instance_variable_set("@#{key}", val) })
  end

  service.update(self, params)
end

#update_positions(positions_params) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/moysklad_integration/entity.rb', line 34

def update_positions(positions_params)
  current_positions = service.get_positions(self)
  current_positions.map! do |current_position|
    current_position.instance_variables.each_with_object({}) do |var, hash|
      key = var.to_s.delete('@').to_sym
      keys_to_compare = positions_params.select { |position| position.dig(:assortment, 'meta', 'uuidHref') == current_position.instance_variable_get(:@assortment).dig('meta', 'uuidHref') }.first&.keys

      next if keys_to_compare.present? && !keys_to_compare&.include?(key)

      hash[key] = current_position.instance_variable_get(var)
    end.merge!(id: current_position.id)
  end

  new_positions = (positions_params - current_positions)
  removed_positions = (current_positions - positions_params)
  service.create_positions(self, new_positions) if new_positions.present?
  service.delete_positions(self, removed_positions) if removed_positions.present?
end