I had to learn to write a Sinatra app and that took little time. Here is the solution which works and I am using ERB templates in this code snippet
my_app.rb (Main sinatra application file)
require 'sinatra'
require 'json'
get '/' do
f = File.open("/home/abcd/my_file.txt","r")
@contents = f.read()
f.close()
erb :home
end
get '/read_file' do
f = File.open("/home/abcd/my_file.txt","r")
contents = f.read()
f.close()
if request.xhr?
halt 200, {:file_contents => contents}.to_json
else
erb :read_file
end
end
views/home.erb
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="data"><%= @contents %></div>
<script type="text/javascript">
function update_data() {
$.ajax({
url: "/read_file",
accepts: "application/json",
dataType: "json",
success: function(data) {
$("#data").html(data.file_contents);
}
});
}
$(document).ready(function() {
#Call update_data every 10 seconds
setInterval(update_data, 10000);
})
</script>
Thank you for asking for code snippet. I learnt a new thing today. Hope this helps.