Sha256: b5c1d687600d0459d6e9a3bc32ce2ec0805c12d588ab1021ddd30601800e039c

Contents?: true

Size: 1.12 KB

Versions: 5

Compression:

Stored size: 1.12 KB

Contents

require 'active_support/concern'

module JupyterOnRails
  module Daru
    module ActiveRecordExt
      extend ::ActiveSupport::Concern

      class_methods do
        def to_df
          relation = all
          loaded_associations =
            %i[includes_values preload_values eager_load_values]
            .map(&relation.method(:send)).reduce(&:|)

          datas = relation.flat_map do |record|
            ret = [record.attributes.symbolize_keys]
            loaded_associations.each do |assoc|
              ret = ret.flat_map do |attrs|
                assocs = record.send(assoc)
                next [attrs] unless assocs.present?

                assocs = [assocs] unless assocs.is_a?(ActiveRecord::Associations::CollectionProxy)
                assocs.map(&:attributes).map do |assoc_attrs|
                  new_attrs = assoc_attrs.transform_keys do |key|
                    "#{assoc}.#{key}".to_sym
                  end
                  attrs.merge(new_attrs)
                end
              end
            end
            ret
          end

          ::Daru::DataFrame.new(datas)
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
jupyter_on_rails-0.5.5 lib/jupyter_on_rails/daru/active_record_ext.rb
jupyter_on_rails-0.5.4 lib/jupyter_on_rails/daru/active_record_ext.rb
jupyter_on_rails-0.5.3 lib/jupyter_on_rails/daru/active_record_ext.rb
jupyter_on_rails-0.5.2 lib/jupyter_on_rails/daru/active_record_ext.rb
jupyter_on_rails-0.5.1 lib/jupyter_on_rails/daru/active_record_ext.rb