ruby-on-railsrubyunixmerb

Prevent Merb from stripping carriage returns?


Every Google search I've tried on this topic has come up with the reverse of my problem!

I'm building a dynamic downloadable text file for users of a web service so they can export their data. I'm using the standard MVC behavior to write the text file on the fly, setting the headers to force a file download like this in the controller:

headers["Content-Disposition"] = "attachment; filename=#{filename}.txt"

I'm running into an issue where Windows end-users are downloading the file and opening it with Notepad - all the line endings are stripped out and it's just one big mess.

I've recreated my view file in as many different ways as I can, saved it as different encodings, recreated it on a Windows machine and triple-checked that it has CRLF at the end of every line.

cat -v app/views/export/export.text.erb shows this:

<%= session.user.username %>'s Data^M
<%= @posts.count %> Posts^M
^M
<% @posts.each do |post| -%>^M
Prompt: <%= post.prompt.title %>^M
Prompt subtitle: <%= post.prompt.subtitle %>^M
^M
Title:    <%= post.title %>^M
Subtitle: <%= post.subtitle %>^M
Created:  <%= post.created_at.to_s %>^M
Updated:  <%= post.updated_at.to_s %>^M
Type:     <%= post.type %>^M
Content:^M
<%= JSON.pretty_generate(post.fields) %>^M
^M
===^M
^M
<% end %>^M

I cannot demand that Windows users use some other text reader. Someone else HAS to have solved this issue before. The other side of this issue: I do not have sudo permissions on this server. I can potentially ask a server admin to install something, but I want to know it's going to work before I do.

Help me Stack Overflow, you're my only hope!


Solution

  • So the solution I finally arrived on is a bit of a hack, and better suggestions are welcome.

    Rather than trying to find where the CR are being stripped out, I stopped forcing the download of the text file with the header (as above) and instead allowed the browser to render the text as it otherwise would. IE and other browsers can all natively handle line endings without needing any interferance, and the user can copy the text file or "Save As" and it will display correctly in Notepad.

    Not perfect, but it'll do for now.