Module: Upgrow::ActiveRecordConversion

Included in:
Repository
Defined in:
lib/upgrow/active_record_conversion.rb

Overview

Offers convenience funcionality to convert Active Records into Models.

Instance Method Summary collapse

Instance Method Details

#_to_model(record) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/upgrow/active_record_conversion.rb', line 27

def _to_model(record)
  associations = record.class.reflections.keys.map do |reflection|
    association = record.association(reflection.to_sym)
    next unless association.loaded?

    [reflection.to_sym, to_model(record.public_send(reflection))]
  end.compact.to_h

  model_class = Object.const_get(Naming.record_to_model(record.class.name))

  attributes = record.attributes.merge(associations)

  model_class.new(**attributes.transform_keys(&:to_sym))
end

#to_model(record_or_enum) ⇒ Model, ...

Converts the given Active Record or Records into Models.

Parameters:

  • record_or_enum (ActiveRecord::Base, Enumerable)

    an Active Record instance or a collection of Records to be converted.

Returns:

  • (Model)

    the Model instance generated based on the single Record given.

  • (Array<Model>)

    the collection of Model instances generated based on the collection of Records provided.

  • (nil)

    if the given value is nil.



16
17
18
19
20
21
22
23
24
# File 'lib/upgrow/active_record_conversion.rb', line 16

def to_model(record_or_enum)
  if record_or_enum.respond_to?(:map)
    record_or_enum.map do |record|
      _to_model(record)
    end
  elsif !record_or_enum.nil?
    _to_model(record_or_enum)
  end
end