Guest User

Untitled

a guest
Jan 17th, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. require "csv"
  2. require File.expand_path(File.dirname(__FILE__) + "/base.rb")
  3.  
  4. # Edit the constants and initialize method for your import data.
  5.  
  6. # Call it like this:
  7. # RAILS_ENV=production CSV_FILE=/path/to/file.csv bundle exec ruby script/import_scripts/moodle_csv.rb
  8.  
  9. class ImportScripts::MoodleCsv < ImportScripts::Base
  10. CSV_FILE_PATH = ENV['CSV_FILE']
  11.  
  12. def initialize
  13. super
  14. @imported_csv = load_csv
  15. end
  16.  
  17. def execute
  18. puts "", "Importing from CSV file..."
  19. import_groups
  20. import_users
  21.  
  22. puts "", "Done"
  23. end
  24.  
  25. def load_csv
  26. # array of arrays
  27. CSV.parse(File.read(CSV_FILE_PATH).scrub)
  28. end
  29.  
  30. def import_groups
  31. puts '', "Importing groups"
  32. # get unique Disiplines for grouping
  33. group_names = @imported_csv[1..-1].map { |u| u[13] }.uniq.compact.map.with_index.to_a
  34. create_groups(group_names) { |g| Hash[:full_name, g[0], :id, g[1]] }
  35. end
  36.  
  37. def import_users
  38. puts '', "Importing users"
  39.  
  40. create_users(@imported_csv[1..-1]) do |u|
  41. {
  42. id: u[0],
  43. username: u[2].to_s.length > 2 ? u[2] : u[6], # use email if no username present
  44. name: [u[4], u[3]].compact.join(' '),
  45. email: clean_email_address(u[6].split(';').first), # a user can have several emails
  46. created_at: Time.now,
  47. custom_fields: {
  48. people_id: u[0],
  49. guid: u[1],
  50. country: u[7],
  51. institute: u[8],
  52. section_1: u[10],
  53. section_2: u[11],
  54. section_3: u[12],
  55. orcid: u[14]
  56. },
  57. post_create_action: proc do |new_user|
  58. if group = Group.find_by(full_name: u[13])
  59. group.users << new_user unless group.users.include?(new_user)
  60. end
  61.  
  62. if remaining_emails = u[6].split(';')[1..-1]
  63. remaining_emails.map! { |e| Hash[:email, clean_email_address(e)] }
  64. new_user.user_emails.create(remaining_emails)
  65. end
  66. end
  67. }
  68. end
  69. end
  70.  
  71. def clean_email_address(email)
  72. email.strip.delete(',')
  73. end
  74. end
  75.  
  76. if __FILE__ == $0
  77. ImportScripts::MoodleCsv.new.perform
  78. end
Add Comment
Please, Sign In to add comment