Class: ImpExp::Serializers::WholeRecords
- Inherits:
-
Object
- Object
- ImpExp::Serializers::WholeRecords
- Defined in:
- app/services/imp_exp/serializers/whole_records.rb
Instance Attribute Summary collapse
-
#columns ⇒ Object
readonly
Returns the value of attribute columns.
Instance Method Summary collapse
- #dump(record, relation_name) ⇒ Object
-
#initialize(columns) ⇒ WholeRecords
constructor
A new instance of WholeRecords.
-
#load(data, model:, relation_name:, scoping_parent: nil) ⇒ Object
rubocop: disable Lint/UnusedMethodArgument.
Constructor Details
#initialize(columns) ⇒ WholeRecords
Returns a new instance of WholeRecords.
8 9 10 |
# File 'app/services/imp_exp/serializers/whole_records.rb', line 8 def initialize(columns) @columns = columns end |
Instance Attribute Details
#columns ⇒ Object (readonly)
Returns the value of attribute columns.
6 7 8 |
# File 'app/services/imp_exp/serializers/whole_records.rb', line 6 def columns @columns end |
Instance Method Details
#dump(record, relation_name) ⇒ Object
12 13 14 15 16 |
# File 'app/services/imp_exp/serializers/whole_records.rb', line 12 def dump(record, relation_name) record.send(relation_name).map do |associated_records| associated_records.slice(columns) end.to_json end |
#load(data, model:, relation_name:, scoping_parent: nil) ⇒ Object
rubocop: disable Lint/UnusedMethodArgument
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'app/services/imp_exp/serializers/whole_records.rb', line 19 def load(data, model:, relation_name:, scoping_parent: nil) return [] if data.blank? begin data = JSON.parse(data) rescue JSON::ParserError => e = e..gsub("859: ", "") # Ruby 3.1 + 3.2 compatibility return [ImpExp::Serializers::Errors::WrongFormat.new("#{relation_name} error | #{}")] end unless data.is_a?(Array) && data.all? { |datum| datum.is_a?(Hash) } return [ImpExp::Serializers::Errors::WrongFormat.new("#{relation_name} should be an array of hashes")] end data = data.map(&:deep_symbolize_keys) relation_class = model.active_record_class.reflections[relation_name.to_s].[:class_name] relation_class ||= relation_name.to_s.classify relation_class = relation_class.constantize data.map do |hash| relation_class.new(hash.slice(*columns)) end end |