Class: ActiveRecord::Bixformer::Model::Csv::Mapped

Inherits:
Base
  • Object
show all
Defined in:
lib/activerecord-bixformer/model/csv/mapped.rb

Instance Attribute Summary

Attributes inherited from Base

#associations, #attributes, #errors, #name, #options, #parent, #preferred_skip_attributes, #translator

Instance Method Summary collapse

Methods inherited from Base

#csv_title, #csv_titles

Methods inherited from Base

#activerecord_constant, #add_association, #find_record_by!, #parent_foreign_key, #parents, #plan, #set_parent, #setup, #should_be_included

Methods included from ImportValueValidatable

#presence_value?

Constructor Details

#initialize(model_or_association_name, options) ⇒ Mapped

Returns a new instance of Mapped.



6
7
8
9
10
11
12
# File 'lib/activerecord-bixformer/model/csv/mapped.rb', line 6

def initialize(model_or_association_name, options)
  super

  unless options[:key] || options[:in]
    raise ArgumentError.new 'Not configure required options : key, in'
  end
end

Instance Method Details

#export(record_or_relation) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/activerecord-bixformer/model/csv/mapped.rb', line 14

def export(record_or_relation)
  # has_many でしか使わない想定なので record_or_relation は ActiveRecord::Relation のはず
  record_of = record_or_relation&.where(@options[:key] => @options[:in])&.index_by(&@options[:key].to_sym) || {}

  errors.clear

  run_bixformer_callback :export do
    @options[:in].inject({}) do |values, key|
      update_translator(key)

      values.merge(do_export(record_of[key]))
    end
  end
end

#import(csv_body_row, parent_record_id = nil) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
# File 'lib/activerecord-bixformer/model/csv/mapped.rb', line 29

def import(csv_body_row, parent_record_id = nil)
  errors.clear

  run_bixformer_callback :import do
    @options[:in].map do |key|
      update_translator(key)

      do_import(csv_body_row, parent_record_id, initializer: { @options[:key] => key })
    end
  end
end

#translate(attribute_name) ⇒ Object



49
50
51
52
53
54
55
56
# File 'lib/activerecord-bixformer/model/csv/mapped.rb', line 49

def translate(attribute_name)
  # TODO: mapped 以外の複数を扱うクラスがあった時の対処が必要
  if parents.find { |parent| parent.is_a?(::ActiveRecord::Bixformer::Model::Csv::Mapped) }
    parents.map { |parent| parent.translator.translate_model }.join + super
  else
    super
  end
end

#verify_csv_titles(csv_title_row) ⇒ Object



41
42
43
44
45
46
47
# File 'lib/activerecord-bixformer/model/csv/mapped.rb', line 41

def verify_csv_titles(csv_title_row)
  @options[:in].all? do |key|
    update_translator(key)

    super
  end
end