Created
January 28, 2018 13:15
-
-
Save michaeltcoelho/6616f3b707692fb4eedaa75d85c299d3 to your computer and use it in GitHub Desktop.
Import users from csv
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'csv' | |
namespace :user_importer do | |
desc "Import users from a CSV file" | |
task :import, [:csv_file] => [:environment] do |_, args| | |
abort "Please specify the CSV file to import" if args[:csv_file].blank? | |
CSV.foreach(args[:csv_file], col_sep: ';', headers: true) do |new_user| | |
user = User.find_by_email(new_user['email']) | |
if user | |
new_groups = new_user_groups(new_user['groups']) - user.groups.map(&:name) | |
user.groups << parse_user_groups(new_groups) | |
puts "User #{new_user['email']} already exists and is not imported." | |
puts ">> #{new_user['email']} was added to #{new_groups.join(',')}" unless new_groups.empty? | |
else | |
u = User.new({ | |
username: new_user['username'] || UserNameSuggester.suggest(new_user['email']), | |
email: new_user['email'], | |
password: SecureRandom.hex, | |
name: new_user['name'], | |
title: new_user['title'], | |
approved: true, | |
approved_by_id: -1, | |
trust_level: TrustLevel[1], | |
}) | |
u.import_mode = true | |
u.groups = parse_user_groups new_user['groups'] | |
if u.save | |
u.activate | |
u.email_tokens.update_all(confirmed: true) | |
puts "Imported #{u.name} (#{u.email}) as #{u.username} to #{u.groups.map(&:name).join(',')}" | |
else | |
puts "Could not import #{u.name} (#{u.email}) due to #{u.errors.messages}" | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment