Sha256: 8cca7bfb693d6d93bf5536de0f2a25583c9539460e69695a5e2e10fd883c5a43

Contents?: true

Size: 1.45 KB

Versions: 1

Compression:

Stored size: 1.45 KB

Contents

require 'active_support/concern'

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

      unless respond_to?(:class_methods)
        def self.class_methods(&class_methods_module_definition)
          mod = const_defined?(:ClassMethods, false) ?
                  const_get(:ClassMethods) :
                  const_set(:ClassMethods, Module.new)

          mod.module_eval(&class_methods_module_definition)
        end
      end

      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

1 entries across 1 versions & 1 rubygems

Version Path
jupyter_on_rails-0.5.6 lib/jupyter_on_rails/daru/active_record_ext.rb