Streaming Files to the Browser with Ruby


I’m trying to find an efficient way to watch the server log on a web page. I don’t mind building a gem; I just want to work out the best way to do it.

Is there a way to keep a stream open to a file with Ruby (not any frameworks) and to the browser? Or will it have to be done by polling the file every x seconds?

That was the question, what i asked Streaming Files to the Browser with Ruby over stackoverflow. I done this job using cramp framework that is written by Pratik Naik.

Cramp:-

Cramp is a fully asynchronous real-time web application framework in Ruby. It is built on top of EventMachine and primarily designed for working with larger number of open connections and providing full-duplex bi-directional communication.

Solution:

1.Ruby 1.9.2+ is the preferred version of Ruby for running Cramp. Installation process is quite straight forward:

$ gem install cramp

2. Create new cramp applicaton

$cramp new my_logger

3. Edit home action and write log solution here

class HomeAction < Cramp::Action
  def start
    File.open("/home/ubuntu/demo/log/development.log", "r").each_line do |line|
      render line
    end
    finish
  end
end

4. And then start the server:

$ bundle exec thin --timeout 0 -R config.ru start

You should be greeted with “logs” on browsing to http://0.0.0.0:3000/

Thats it,  Thanks Pratik Naik for such a great work.

Advertisements

3 thoughts on “Streaming Files to the Browser with Ruby

  1. Andrew Davis says:

    I am trying to accomplish this same thing. But I need the content of the file to be streamed to a particular location in my page. Any way to append it in the html with javascript?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s