Question

I would simply like to display a .txt file located in my public directory onto a page. I apologise that this may seem novice but I am new to Ruby.

So far the ruby sinatra code reads:

get '/create' do
    logfile = File.open("logfile.txt")
    erb :create
end

and the erb reads:

<h2>Text file:</h2>
<%= logfile %>

Can someone tell me what I need to display this text file on my page?

Was it helpful?

Solution 3

You can do as below :

sinatra code :

get '/create' do
    @logfile = File.open("logfile.txt","r")
    erb :create
    @logfile.close
end

file.erb

<h2>Text file:</h2>
<% @logfile.each_line do |line| %>
  <%= line %>
<% end %>

Or you can use File#read :

file.erb

<h2>Text file:</h2>
<%= @logfile.read %>

OTHER TIPS

Another way to show .txt file with Sinatra(without erb).
in your script:

get '/' do
  send_file 'views/file.txt'
end

puts file.txt with content:

Heloo ! somebody here?


enter image description here

I think you were aiming for something like this:

get '/create' do
    @logfile = File.read("logfile.txt")
    erb :create
end

In the Erb:

<h2>Text file:</h2>
<%= @logfile %>

(Note that I would probably also put it inside a div with overflow: auto style applied)

Following this applied a secure solution as I need to output the text file inside my other HTML.

require 'rack/utils'

get '/logfile' do
    File.open('./public/log.txt','r') do |file|
        @logtext = Rack::Utils.escape_html(file.read) # this will assure security
    end
    erb :logfile
end

views/logfile.erb

<h1>Log file</h1>
<pre><%= @logtext %></pre>

Suppose our logs are less secure than our site code, and some bad person did a bad thing:

[INFO] User Admin successfully logged in.
[ERROR] User Frog failed to log in.
</pre><script>alert('Do harmful thing!')</script>
[INFO] User Admin successfully logged in.

The output will be exactly the above text (without the pop-up message).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top