def import_csv
model_name = params[:table_name].split('.')[0].singularize.capitalize # 1) "Products.csv"
@parsed_file=CSV.parse(params[:dump][:file].read) # 2)
# get the model object
model = get_model_object_by_string(model_name) # 3)
# get the headers 4)
headers = get_headers(@parsed_file)
@parsed_file.shift # delete first row in array (which was comprized of column names, not data)
gc_count=0
@parsed_file.each do |row|
t=model.new # t as in table of course
i=0
headers.each do |column_title| # 5)
eval "t.#{column_title} = #{row[i]}" # if it's a string, it needs to be handled differently...
i += 1
end
.
.
.
See,
1) I take the table name, and convert it into a string which is in effect the model name
2) Then I parse the CSV data into rows of fields.
3) The the fun starts, and I return a reference to the object of the name model_name!
4) I do boring header stuff since the first row of that CSV is headers...
5) Now the fifth section is where I run into my problem...
I'm trying to set a variable on my ActiveRecord model instance... but all I have to go on is the name of the variable as a STRING =(
My solution was to use eval to have it do the work for me, but that method is discouraged on the web. It also means I'll need to code at least three different ways of setting the variable... If it's a string, I need to put quotes around the data in the eval call... If it's a plain old integer, I just leave it as is. And if it's a decimal, I need to look up how ruby does decimals and format the eval thing accordingly. And what about when I've got to do date times in other tables?
I've coded this type of thing before in C# and it feels just awful. Is this the right way to do things?
This post has been edited by NotarySojac: 23 December 2011 - 10:50 PM

New Topic/Question
Reply




MultiQuote





|