Class: Daru::IO::Importers::ActiveRecord

Inherits:
Base
  • Object
show all
Defined in:
lib/daru/io/importers/active_record.rb

Overview

ActiveRecord Importer Class, that extends from_activerecord method to Daru::DataFrame

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

guess_parse, read

Methods inherited from Base

#optional_gem

Constructor Details

#initializeActiveRecord

Checks for required gem dependencies of ActiveRecord Importer



12
13
14
# File 'lib/daru/io/importers/active_record.rb', line 12

def initialize
  optional_gem 'activerecord', '~> 4.0', requires: 'active_record'
end

Class Method Details

.from(relation) ⇒ Daru::IO::Importers::ActiveRecord

Loads data from a given relation

Examples:

Loading from a ActiveRecord instance

instance = Daru::IO::Importers::ActiveRecord.from(Account.all)

Parameters:

  • relation (ActiveRecord::Relation)

    A relation to be used to load the contents of DataFrame

Returns:



27
28
29
30
# File 'lib/daru/io/importers/active_record.rb', line 27

def from(relation)
  @relation = relation
  self
end

Instance Method Details

#call(*fields) ⇒ Daru::DataFrame

Imports a Daru::DataFrame from an ActiveRecord Importer instance

Examples:

Importing from an instance without specifying fields

instance.call

#=> #<Daru::DataFrame(2x3)>
#=>        id  name   age
#=>   0     1 Homer    20
#=>   1     2 Marge    30

Importing from an instance with specific fields

instance.call(:id, :name)

#=> #<Daru::DataFrame(2x2)>
#=>        id  name
#=>   0     1 Homer
#=>   1     2 Marge

Parameters:

  • fields (String or Array of Strings)

    A set of fields to load from.

Returns:



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/daru/io/importers/active_record.rb', line 53

def call(*fields)
  @fields = fields

  if @fields.empty?
    records = @relation.map { |record| record.attributes.symbolize_keys }
    return Daru::DataFrame.new(records)
  else
    @fields.map!(&:to_sym)
  end

  vectors = @fields.map { |name| [name, Daru::Vector.new([], name: name)] }.to_h

  Daru::DataFrame.new(vectors, order: @fields).tap do |df|
    @relation.pluck(*@fields).each do |record|
      df.add_row(Array(record))
    end
    df.update
  end
end

#from(relation) ⇒ Daru::IO::Importers::ActiveRecord

Loads data from a given relation

Examples:

Loading from a ActiveRecord instance

instance = Daru::IO::Importers::ActiveRecord.from(Account.all)

Parameters:

  • relation (ActiveRecord::Relation)

    A relation to be used to load the contents of DataFrame

Returns:



27
28
29
30
# File 'lib/daru/io/importers/active_record.rb', line 27

def from(relation)
  @relation = relation
  self
end