I have the following helper method that I’m using to upload some records to Dropbox. For each of the three models (logbooks, aircraft, and approaches), I’m doing the exact same thing. I’d like to make this more DRY and only have the code once, but I don’t understand how to reference a model in an abstracted way.
Any recommendations?
#------------------------------------------------------------
# Upload entries to Dropbox
#------------------------------------------------------------
def upload_items(items, folder, client)
# Go through each item and upload it to Dropbox
items.each do |item|
if folder == 'logbook'
# Get the file from the database to upload
@logbook = current_user.logbooks.find_by_sync_id(item)
# Upload it
uploaded_file = client.put_file("/logbook/#{item}.json",@logbook.to_json, overwrite = true)
# Reset the updated_flag in the database
@logbook.update_attributes(updated_flag: 0)
elsif folder == 'aircraft'
# Get the file from the database to upload
@aircraft = current_user.aircrafts.find_by_sync_id(item)
# Upload it
uploaded_file = client.put_file("/aircraft/#{item}.json",@aircraft.to_json, overwrite = true)
# Reset the updated_flag in the database
@aircraft.update_attributes(updated_flag: 0)
elsif folder == 'approaches'
# Get the file from the database to upload
@approach = current_user.approaches.find_by_sync_id(item)
# Upload it
uploaded_file = client.put_file("/approaches/#{item}.json",@approach.to_json, overwrite = true)
# Reset the updated_flag in the database
@approach.update_attributes(updated_flag: 0)
end
end
end
Ruby 1.9.3, Rails 3.2.8
This will do the job.
The critical part below is
current_user.public_send(folder.to_sym)which takes the folder name and converts it to a message to send to the current_user.