0.0
No commit activity in last 3 years
No release in over 3 years
Rails Importer (CSV, XLS, XML)
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Runtime

>= 4, < 7
~> 1.1, >= 1.1.4
 Project Readme

Rails Importer

Rails Importer (XML, XLS, CSV)

How to install

Add it to your Gemfile:

gem 'rails-importer'

Run the following command to install it:

$ bundle install
$ rails generate rails_importer:install

Generators

You can generate importers app/importers/example_importer.rb

$ rails generate rails_importer:importer example

Generator will make a file with content like:

class ExampleImporter < RailsImporter::Base

  importer do
    fields :name, :email, :age
    #or fields({:name => "Name", :email => "E-mail", :age => "Idade"})
    each_record do |record, params|
    
      MyModel.find_or_create_by(name: record[:name], email: record[:email], age: record[:age])
      
      return record # or return wherever
    end
  end
  
  # importer :simple do
  #   csv_params col_sep: ';'
  #   xml_structure :root, :row
  #   fields :name, :email, :age
  #   each_record do |record, params|
  #       ...
  #   end
  # end

end

How to use

You can call import from Importers objects: file param must be an object that responds to .path method

    file = params[:import][:file]
    records = ExampleImporter.import(file)

Or with context:

    file = params[:import][:file]
    records = ExampleImporter.import(file, context: :simple)

Overwrite default fields (called in the block importer do):

    file = params[:import][:file]
    records = ExampleImporter.import(file, fields: [:name, :email, :age])

With extra params:

    file = params[:import][:file]
    records = ExampleImporter.import(file, {user: 'john@mail.com'})

Then inside each record you can get params:

class ExampleImporter < RailsImporter::Base
  importer do
    # ...
    each_record do |record, params|
      # ...
      params[:user]
      # ...
    end
    # ...
  end
end

With full options:

    file = params[:import][:file]
    records = ExampleImporter.import(file,
      context: :simple,
      fields: [:name, :email, :age],
      {user: 'john@mail.com', account: '1'})

To return imported values, you need to return values inside of each_record:

class ExampleImporter < RailsImporter::Base
  importer do
    # ...
    each_record do |record, params|
      # ...
      u = Model.new(record)
      u.created_by = params[:user]
      ok = !!u.save
      return {record: u, success: ok}
    end
    # ...
  end
end
records = ExampleImporter.import(file, {user: 'john@mail.com'})
# [{record: ..., success: true}, {record: ..., success: false}]