small medium large xlarge

Eric j. gruber_pragsmall
30 Sep 2009, 15:30
Eric J. Gruber (10 posts)

If I was to include a file (such as in a template) in php to use across a large number of pages, I would write this:

<?php include ('navigation.html'); ?>

In turn, every time I used this code, it would “include” (or better put, display) the content of navigation.html in the browser.

I can’t figure out how to do this is Rails. When building my layouts, how can I include a file like this, like I would in PHP. I have files I’d like to include remotely, but not sure how to get this done.

Any ideas?

Eric j. gruber_pragsmall
30 Sep 2009, 18:23
Eric J. Gruber (10 posts)

To answer my own question, one must enable Ruby’s open-uri module.

So, in application_controller.rb, put this line after class ApplicationController < ActionController::Base

require 'open-uri'

Then, what I did was put this in my layout file:

<%= open("").read %>

This works in the same manner as PHP’s include() or readfile().

I’ll save the argument as to whether this is best from a performance or security standpoint for someone else.

30 Sep 2009, 19:38
Derek DeVries (18 posts)

We have a section on the Ruby equivalents of require/include at the end of Chapter 11 in the book starting on page 309. In Rails you would typically use partials (discussed starting in section 5.9 starting on page 136). This would look something like @render :partial => “navigation”@ to include the navigation template within a another template. Although this might not be the best example since you wouldn’t need to duplicate navigation markup if you were using a Rails ERB layout (discussed starting on in section 5.11 on page 144).

If you really need to include a *remote* html partial file within another template (which is very unusual in Rails and I wouldn’t recommend) – I don’t think the way you’re doing it is going to be very fast (or secure). You would probably want to read, sanitize, and cache the data somehow before rendering it in your app.

Eric j. gruber_pragsmall
01 Oct 2009, 14:15
Eric J. Gruber (10 posts)

Derek, thanks for that.

In my situation, both servers are under my control, so the only risk of uploading malicious code would be from me. Also, in this instance, any performance hit I would take from this method is acceptable as the use is very small.

You must be logged in to comment