Include contents of a file in a view


#1

Guys,

I have an application and part of its function is to display html
marked up text files to the users, inlined in the current page
layout. I have the files stored outside the Rails app directories,
and not in the database.

What I want to do is something like this in my view:

Viewing contents of filename

<%= send_file( ... ) -%>

So that my normal layout gets put around the included file.

I know I could easily create a helper, say, my_send_file that takes
the filename and returns its contents, but it means the entire file
will be pulled into memory (the files could be a reasonable size, but
not massive!). I guess if the files were in the database I would have
to pull the data out of the database into memory anyway, making this
an equivalent process.

Basically I want to know

  1. Is there a builtin way to do this, or will I just go ahead and
    create a helper (I don’t think the send_file method is going to be any
    good for me here).
  2. When rendering a large page, does Rails stream it to the user, or
    does it build it all in memory, and then stream it? Just curious on
    this one …

Thanks,

Stephen.


#2

Open the file, iterate through the lines and parse it with CodeRay or
something similar to get syntax highlighting.

File.open(“the_filename.html”, “r”).each { |line| puts line }

Etc.

Not sure about the 2nd one. I’m pretty sure it keeps the page in
memory until it’s sent to the user, then removes it from memory - at
least that’s what makes most sense.


#3

I’m almost 100% it’s not possible to read an entire file to send to
the user without reading it into memory first. But you shouldn’t be
worried about that, memory is fast and I’m assuming your files are
less than 1MB (since they are HTML). If they are bigger than 1MB, then
you should be worried about bandwidth and browsers rendering 1MB of
HTML.

I hope that helps.


#4

On Jul 6, 1:27 pm, August L. removed_email_address@domain.invalid wrote:

an equivalent process.
Thanks,

Stephen.

Yea thats pretty much what I did in a help.

Cheers for the hint on Coderay - that may be useful for some of the
stuff I need to do!


#5

On Jul 6, 5:20 pm, AryaAsemanfar removed_email_address@domain.invalid wrote:

I’m almost 100% it’s not possible to read an entire file to send to
the user without reading it into memory first. But you shouldn’t be
worried about that, memory is fast and I’m assuming your files are
less than 1MB (since they are HTML). If they are bigger than 1MB, then
you should be worried about bandwidth and browsers rendering 1MB of
HTML.

I hope that helps.

Reckoned that was the case - cheers for the input, thought it would be
worth checking just incase!