[Awesome Ruby Gem] Use active_importer gem to load tabular data from spreadsheets or CSV files into any ActiveRecord-like ORM

active_importer

active_importer allows you to define importers that load tabular data from spreadsheets or CSV files into any ActiveRecord-like ORM.

Installation

You can install it as a gem:

1
$ gem install active_importer

or add it into a Gemfile (Bundler):

1
2
3
4
5
# Gemfile

# continuum/active_importer: Define importers that load tabular data from spreadsheets or CSV files into any ActiveRecord-like ORM.
# https://github.com/continuum/active_importer
gem 'active_importer', '0.2.6'

Usages

Importers are classes that you can instruct on how to import data into data models.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# app/imports/employee_import.rb

class EmployeeImporter < ActiveImporter::Base
imports Employee

fetch_model do
Employee.where({
first_name: row['First name'],
last_name: row['Last name'],
}).first_or_initialize
end

column 'First name', :first_name

column 'Last name', :last_name

column 'Department', :department do |department_name|
Department.find_by(name: department_name)
end

column 'Salary', :salary, optional: true

on :row_error do |ex|
logger.error("Couldn't import row #{row_index}: #{ex.message}")
end

on :row_processing do
model.owner_id = params[:owner_id]
end

private

def logger
@logger ||= Rails.logger
end
end

Once defined, importers can be invoked to import a given data file.

1
EmployeeImporter.import('file.xls', params: { owner_id: @user.id })

See Home · continuum/active_importer Wiki - https://github.com/continuum/active_importer/wiki to learn more.

References

[1] continuum/active_importer: Define importers that load tabular data from spreadsheets or CSV files into any ActiveRecord-like ORM. - https://github.com/continuum/active_importer

[2] Active Importer by continuum - http://continuum.github.io/active_importer/

[3] active_importer | RubyGems.org | your community gem host - https://rubygems.org/gems/active_importer/

[4] Home · continuum/active_importer Wiki - https://github.com/continuum/active_importer/wiki