Module: RailsAdminImport::Import::ClassMethods

Defined in:
lib/rails_admin_import/import.rb

Instance Method Summary collapse

Instance Method Details

#belongs_to_fieldsObject



41
42
43
44
# File 'lib/rails_admin_import/import.rb', line 41

def belongs_to_fields
  attrs = self.reflections.select { |k, v| v.macro == :belongs_to }.keys
  attrs - RailsAdminImport.config(self).excluded_fields 
end

#file_fieldsObject



9
10
11
12
13
14
15
# File 'lib/rails_admin_import/import.rb', line 9

def file_fields
  attrs = []
  if self.methods.include?(:attachment_definitions) && !self.attachment_definitions.nil?
    attrs = self.attachment_definitions.keys
  end
  attrs - RailsAdminImport.config(self).excluded_fields 
end

#import_fieldsObject



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/rails_admin_import/import.rb', line 17

def import_fields
  fields = []  

  fields = self.new.attributes.keys.collect { |key| key.to_sym }
  
  self.belongs_to_fields.each do |key|
    fields.delete("#{key}_id".to_sym)
  end
  
  self.file_fields.each do |key|
    fields.delete("#{key}_file_name".to_sym)
    fields.delete("#{key}_content_type".to_sym)
    fields.delete("#{key}_file_size".to_sym)
    fields.delete("#{key}_updated_at".to_sym)
  end
 
  excluded_fields = RailsAdminImport.config(self).excluded_fields 
  [:id, :created_at, :updated_at, excluded_fields].flatten.each do |key|
    fields.delete(key)
  end
  
  fields
end

#import_initialize(row, map, update) ⇒ Object



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/rails_admin_import/import.rb', line 137

def import_initialize(row, map, update)
  new_attrs = {}
  self.import_fields.each do |key|
    new_attrs[key] = row[map[key]] if map[key]
  end

  item = nil
  if update.present?
    item = self.send("find_by_#{update}", row[map[update]])
  end 

  if item.nil?
    item = self.new(new_attrs)
  else
    item.attributes = new_attrs.except(update.to_sym)
    item.save
  end

  item
end

#many_fieldsObject



46
47
48
49
50
51
52
53
54
55
# File 'lib/rails_admin_import/import.rb', line 46

def many_fields
  attrs = []
  self.reflections.each do |k, v|
    if [:has_and_belongs_to_many, :has_many].include?(v.macro)
      attrs << k.to_s.singularize.to_sym
    end
  end

  attrs - RailsAdminImport.config(self).excluded_fields 
end

#run_import(params) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/rails_admin_import/import.rb', line 57

def run_import(params)
  begin
    if !params.has_key?(:file)
      return results = { :success => [], :error => ["You must select a file."] }
    end

    if RailsAdminImport.config.logging
      FileUtils.copy(params[:file].tempfile, "#{Rails.root}/log/import/#{Time.now.strftime("%Y-%m-%d-%H-%M-%S")}-import.csv")
    end

    text       = File.read(params[:file].tempfile)
    clean      = text.force_encoding('BINARY').encode('UTF-8', :undef => :replace, :replace => '').gsub(/\n$/, '')
    file_check = CSV.new(clean)
    logger     = ImportLogger.new
     
    if file_check.readlines.size > RailsAdminImport.config.line_item_limit
      return results = { :success => [], :error => ["Please limit upload file to #{RailsAdminImport.config.line_item_limit} line items."] }
    end
  
    map = {}
   
    file = CSV.new(clean)
    file.readline.each_with_index do |key, i|
      if self.many_fields.include?(key.to_sym)
        map[key.to_sym] ||= []
        map[key.to_sym] << i
      else
        map[key.to_sym] = i 
      end
    end
   
    update = params.has_key?(:update_if_exists) && params[:update_if_exists] ? params[:update_lookup].to_sym : nil
  
    if update && !map.has_key?(params[:update_lookup].to_sym)
      return results = { :success => [], :error => ["Your file must contain a column for the 'Update lookup field' you selected."] }
    end 
    
    results = { :success => [], :error => [] }
    
    associated_map = {}
    self.belongs_to_fields.flatten.each do |field|
      associated_map[field] = field.to_s.classify.constantize.all.inject({}) { |hash, c| hash[c.send(params[field]).to_s] = c.id; hash }
    end
    self.many_fields.flatten.each do |field|
      associated_map[field] = field.to_s.classify.constantize.all.inject({}) { |hash, c| hash[c.send(params[field]).to_s] = c; hash }
    end
   
    label_method = RailsAdminImport.config(self).label
  
    file.each do |row|
      object = self.import_initialize(row, map, update)
      object.import_belongs_to_data(associated_map, row, map)
      object.import_many_data(associated_map, row, map)
      object.before_import_save(row, map)
  
      object.import_files(row, map)

      verb = object.new_record? ? "Create" : "Update"
      if object.errors.empty?
        if object.save
          logger.info "#{Time.now.to_s}: #{verb}d: #{object.send(label_method)}"
          results[:success] << "#{verb}d: #{object.send(label_method)}"
          object.after_import_save(row, map)
        else
          logger.info "#{Time.now.to_s}: Failed to #{verb}: #{object.send(label_method)}. Errors: #{object.errors.full_messages.join(', ')}."
          results[:error] << "Failed to #{verb}: #{object.send(label_method)}. Errors: #{object.errors.full_messages.join(', ')}."
        end
      else
        logger.info "#{Time.now.to_s}: Errors before save: #{object.send(label_method)}. Errors: #{object.errors.full_messages.join(', ')}."
        results[:error] << "Errors before save: #{object.send(label_method)}. Errors: #{object.errors.full_messages.join(', ')}."
      end
    end
    
    results
  rescue Exception => e
    logger.info "#{Time.now.to_s}: Unknown exception in import: #{e.inspect}"
    return results = { :success => [], :error => ["Could not upload. Unexpected error: #{e.to_s}"] }
  end
end