Search code examples
rubylocalabsolute-pathwebrick

How can I use local resources on a server?


How can I use local resources like css, js, png, etc. within a dynamically rendered page using webrick? In other words, how are things like Ruby on Rails linking made to work? I suppose this is one of the most basic things, and there should be a simple way to do it.

Possible Solution

I managed to do what I wanted using two servlets as follows:

require 'webrick' 

class WEBrick::HTTPServlet::AbstractServlet
  def do_GET request, response
    response.body = '<html>
      <head><base href="http://localhost:2000"/></head>
      <body><img src="path/image.png" /></body>
    </html>'
  end
end

s1 = WEBrick::HTTPServer.new(Port: 2000, BindAddress: "localhost")
s2 = WEBrick::HTTPServer.new(Port: 3000, BindAddress: "localhost")
%w[INT TERM].each{|signal| trap(signal){s1.stop}}
%w[INT TERM].each{|signal| trap(signal){s2.shutdown}}
s1.mount("/", WEBrick::HTTPServlet::FileHandler, '/')
s2.mount("/", WEBrick::HTTPServlet::AbstractServlet)

Thread.new{s1.start}
s2.start

Is this the right way to do it? I do not feel so. In addition, I am not completely satisfied with it. For one thing, I do not like the fact that I have to specify http://localhost:2000 in the body. Another is the use of thread does not seem right. Is there a better way to do this? If you think this is the right way, please answer so.


Solution

  • I finally found out that I can mount multiple servlets on a single server. It took a long time until I found such example.

    require 'webrick' 
    
    class WEBrick::HTTPServlet::AbstractServlet
      def do_GET request, response
        response.body = '<html>
          <head><base href="/resource/"/></head>
          <body>
            <img src="path_to_image/image.png";alt="picture"/>
            <a href="path_to_directory/" />link</a>
            ...
          </body>
        </html>'
      end
    end
    
    server = WEBrick::HTTPServer.new(Port: 3000, BindAddress: "localhost")
    %w[INT TERM].each{|signal| trap(signal){server.shutdown}}
    server.mount("/resource/", WEBrick::HTTPServlet::FileHandler, '/')
    server.mount("/", WEBrick::HTTPServlet::AbstractServlet)
    server.start
    

    The path /resource/ can be anything else. The link will now correctly redirect to the expected directory, showing that there is no access permission, which indicates that things are working right; it's now just a matter of permission.