I installed the camt_parser gem in my rails app. My goal is to upload and parse camt_file (.xml).
It works perfectly when I parse from a local file this way:
require 'camt_parser'
require 'camt'
camt = CamtParser::File.parse 'CAMT053_140518.xml'
puts camt.group_header.creation_date_time
camt.statements.each do |statement|
statement.entries.each do |entry|
# Access individual entries/bank transfers
# puts "->"
puts entry.description
puts entry.debit
p entry.transactions[0].iban
p entry.transactions[0].transaction_id
puts entry.transactions[0].debitor.iban
end
end
But when I try to upload it from my view as a file using this code:
<%= form_tag '/patient_page/import_camt', :multipart => true do %>
<label for="file">Upload text File</label> <%= file_field_tag "file" %>
<%= submit_tag %>
<% end %>
and
the corresponding method:
def import_camt
uploaded_file = params[:file]
parsed_file = uploaded_file.read
camt = CamtParser::File.parse uploaded_file
puts camt.group_header.creation_date_time
camt.statements.each do |statement|
statement.entries.each do |entry|
puts entry.description
puts entry.debit
p entry.transactions[0].iban
p entry.transactions[0].transaction_id
puts entry.transactions[0].debitor.iban
end
end
end
I get the following error
"no implicit conversion of ActionDispatch::Http::UploadedFile into String" at the line when I try to parse the uploaded file.
Any hints?
Thx!
CamtParser::File.parse
is expecting a file path but you are passing an ActionDispatch::Http::UploadedFile
object.
When you upload a file in rails the file is wrapped in an instance of ActionDispatch::Http::UploadedFile
. To access the file itself there is an attribute called tempfile
.
This will return the Tempfile
that represents the actual file that is being uploaded. A Tempfile
has a path
method which is the path to the file itself so since CamtParser::File.parse
is expecting a file path it can be called as follows
CamtParser::File.parse(uploaded_file.tempfile.path)
CamtParser
also has a String
class that can parse an appropriate string so you could call this as
CamtParser::String.parse(uploaded_file.read)
This works because ActionDispatch::Http::UploadedFile
exposes the method read
which is the same as calling uploaded_file.tempfile.read