Class: Import
- Inherits:
-
ActiveRecord::Base
- Object
- ActiveRecord::Base
- Import
show all
- Defined in:
- app/models/import.rb
Overview
Table name: imports
id :integer not null, primary key
assignment :text
target_model :string(255)
successful :boolean
upload_id :integer
separator :string(255) default(",")
result :text
created_at :datetime not null
updated_at :datetime not null
Constant Summary
collapse
- BlockedAttributes =
["id", "created_at", "updated_at", "url_name", "slug"]
Instance Method Summary
collapse
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(meth, *args, &block) ⇒ Object
40
41
42
43
44
|
# File 'app/models/import.rb', line 40
def method_missing(meth, *args, &block)
if meth.to_s.include?("assignment_") && self.assignment.present?
self.assignment[meth.to_s.split("_")[1]]
end
end
|
Instance Method Details
#analyze_csv ⇒ Object
23
24
25
26
27
28
29
30
|
# File 'app/models/import.rb', line 23
def analyze_csv
result = []
data = CSV.read(self.upload.image.path, {:col_sep => self.separator})
data.first.each_with_index do |a, index|
result << [a,index.to_s]
end
@analyze_csv ||= result
end
|
#get_association_names ⇒ Object
36
37
38
|
# File 'app/models/import.rb', line 36
def get_association_names
self.target_model.constantize.reflect_on_all_associations.collect { |r| r.name }
end
|
#get_model_attributes ⇒ Object
32
33
34
|
# File 'app/models/import.rb', line 32
def get_model_attributes
@get_model_attributes ||= eval("#{self.target_model}.new.attributes").delete_if{|a| BlockedAttributes.include?(a) }.keys
end
|
#run! ⇒ Object
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
# File 'app/models/import.rb', line 50
def run!
self.result = []
count = 0
CSV.foreach(self.upload.image.path, {:col_sep => self.separator} ) do |row|
new_object = self.target_model.constantize.new
self.assignment.each do |key,value|
next if value.blank?
attr_name = key
attr_value = row[value.to_i]
new_object.send("#{attr_name}=", attr_value)
end
unless new_object.save
self.result << "#{count} - #{new_object.errors.messages}"
end
count += 1
end
self.save
end
|
#status ⇒ Object
46
47
48
|
# File 'app/models/import.rb', line 46
def status
@status ||="ready to import"
end
|