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, #name, #options, #parent, #preferred_skip_attributes, #translator

Instance Method Summary collapse

Methods inherited from Base

#csv_title

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

#csv_titlesObject



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

def csv_titles
  @options[:in].flat_map do |key|
    update_translator(key)

    super
  end
end

#export(record_or_relation) ⇒ Object



14
15
16
17
18
19
20
21
22
23
# 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]) || {}

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

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

#import(csv_body_row, parent_record_id = nil) ⇒ Object



25
26
27
28
29
30
31
# File 'lib/activerecord-bixformer/model/csv/mapped.rb', line 25

def import(csv_body_row, parent_record_id = nil)
  @options[:in].map do |key|
    update_translator(key)

    super
  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



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

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

    return false unless super
  end
end