Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require "csv"
- require File.expand_path(File.dirname(__FILE__) + "/base.rb")
- # Edit the constants and initialize method for your import data.
- # Call it like this:
- # RAILS_ENV=production CSV_FILE=/path/to/file.csv bundle exec ruby script/import_scripts/moodle_csv.rb
- class ImportScripts::MoodleCsv < ImportScripts::Base
- CSV_FILE_PATH = ENV['CSV_FILE']
- def initialize
- super
- @imported_csv = load_csv
- end
- def execute
- puts "", "Importing from CSV file..."
- import_groups
- import_users
- puts "", "Done"
- end
- def load_csv
- # array of arrays
- CSV.parse(File.read(CSV_FILE_PATH).scrub)
- end
- def import_groups
- puts '', "Importing groups"
- # get unique Disiplines for grouping
- group_names = @imported_csv[1..-1].map { |u| u[13] }.uniq.compact.map.with_index.to_a
- create_groups(group_names) { |g| Hash[:full_name, g[0], :id, g[1]] }
- end
- def import_users
- puts '', "Importing users"
- create_users(@imported_csv[1..-1]) do |u|
- {
- id: u[0],
- username: u[2].to_s.length > 2 ? u[2] : u[6], # use email if no username present
- name: [u[4], u[3]].compact.join(' '),
- email: clean_email_address(u[6].split(';').first), # a user can have several emails
- created_at: Time.now,
- custom_fields: {
- people_id: u[0],
- guid: u[1],
- country: u[7],
- institute: u[8],
- section_1: u[10],
- section_2: u[11],
- section_3: u[12],
- orcid: u[14]
- },
- post_create_action: proc do |new_user|
- if group = Group.find_by(full_name: u[13])
- group.users << new_user unless group.users.include?(new_user)
- end
- if remaining_emails = u[6].split(';')[1..-1]
- remaining_emails.map! { |e| Hash[:email, clean_email_address(e)] }
- new_user.user_emails.create(remaining_emails)
- end
- end
- }
- end
- end
- def clean_email_address(email)
- email.strip.delete(',')
- end
- end
- if __FILE__ == $0
- ImportScripts::MoodleCsv.new.perform
- end
Add Comment
Please, Sign In to add comment