I'm trying to do some file-reading in VoltRb and embed the contents of those files in my views. I initially planned that I would read the files on the server-side (since the client-side doesn't support file-reading), and then pass the strings of those files on to the client, but it seems that I'm getting an empty string for my files on the client.
Here is some code to demonstrate my problem:
file.txt
file contents
main_controller.rb
if RUBY_ENGINE == 'ruby'
file = File.open("app/files_to_read/lib/file.txt", "r")
$file_text = file.read
file.close
puts $file_text # returns "file contents" on the server side
puts $file_text.class # returns "String" on the server side
end
module Main
class MainController < Volt::ModelController
model :page
def index
page._text = $file_text
puts $file_text # returns an empty string in the browser console
end
...
end
end
index.html
<:Title>
Home
<:Body>
<h1>Home</h1>
<p>{{ _text }}</p>
<!-- ^ an empty string -->
My directory tree looks like this:
app
├── files_to_read
│ └── lib
│ └── file.txt
└── main
├── assets
├── config
├── controllers
│ └── main_controller.rb
├── lib
├── tasks
└── views
└── main
├── about.html
├── index.html
└── main.html
Why am I getting an empty string for my file and how do I fix this?
So one thing to keep in mind is that controllers will be run twice, once on the client, and once on the server. So the client one will be a different instance than the ones on the server, so they won't have access to the $file_text global.
What you can do though is create a task that reads the file and then returns the text of the file. Check out @RickCarlino's excellent tasks tutorial video: http://datamelon.io/blog/2015/creating-volt-task-objects.html
Thanks