module Upgrow::ActiveRecordConversion

Offers convenience funcionality to convert Active Records into Models.

Public Instance Methods

_to_model(record) click to toggle source

@private

# 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) click to toggle source

Converts the given Active Record or Records into Models.

@param record_or_enum [ActiveRecord::Base, Enumerable] an Active Record

instance or a collection of Records to be converted.

@return [Model] the Model instance generated based on the single Record

given.

@return [Array<Model>] the collection of Model instances generated based

on the collection of Records provided.

@return [nil] if the given value is nil.

# 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