Sha256: de98c3d056ec99d94c0c041c5e35008c93905feb4cecd1d8196181b32bfa74e5
Contents?: true
Size: 1.4 KB
Versions: 1
Compression:
Stored size: 1.4 KB
Contents
# frozen_string_literal: true module Upgrow # Offers convenience funcionality to convert Active Records into Models. module ActiveRecordConversion # 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. 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 # @private def _to_model(record) associations = record.class.reflections.keys.map do |reflection| association = record.association(reflection.to_sym) next unless association.loaded? name = reflection.sub('_record', '').to_sym [name, to_model(record.public_send(reflection))] end.compact.to_h model_class = Object.const_get(record.class.name.delete_suffix('Record')) attributes = record.attributes.merge(associations) model_class.new(**attributes.transform_keys(&:to_sym)) end end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
upgrow-0.0.4 | lib/upgrow/active_record_conversion.rb |