How is it possiable to open an view a txt file with rails?
Example I have test.txt:
Test test test test
Then I have my test.html.erb:
Here I want to view test.txt
How is it possiable to open an view a txt file with rails?
Example I have test.txt:
Test test test test
Then I have my test.html.erb:
Here I want to view test.txt
You can either render an arbitrary file or use send_file
: 3.1 or < 3.1
Another possibility is:
Here is the test.txt file: <%= File.read("test.txt") %>
In some cases (when the file is not small and loading it is connected with a delay), I prefer to load the page content and then to use jQuery
ajax request to load the file content.
For example, let's say I have a model with file path attribute. In the view
layout I am doing something like this:
<pre data-source=" <%= (@file.path) %>"></pre>
Then in the corresponding js
file I am loading the context like this:
$(document).ready ->
$.ajax(
url: $("pre").data("source")
context: document.body
).done (response) ->
$("pre").html response
return
return
Of course you can check the jQuery ajax documentation for more options. For example, you can render the pre
tag with loading
like this:
<pre data-source=" <%= (@file.path) %>"><div class="loading"></pre>
or use other jQuery
animations as well.
Here is the test.txt file:
<%= File.read(File.join(Rails.root, 'your_folder','your_folder','test.txt'))%>