Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access html request parameters for a .rhtml page served by webrick?

I'm using webrick (the built-in ruby webserver) to serve .rhtml files (html with ruby code embedded --like jsp).

It works fine, but I can't figure out how to access parameters (e.g. http://localhost/mypage.rhtml?foo=bar) from within the ruby code in the .rhtml file. (Note that I'm not using the rails framework, only webrick + .rhtml files)

Thanks

like image 650
cibercitizen1 Avatar asked Jan 22 '23 03:01

cibercitizen1


2 Answers

According to the source code of erbhandler it runs the rhtml files this way:

    Module.new.module_eval{
      meta_vars = servlet_request.meta_vars
      query = servlet_request.query
      erb.result(binding)
    }

So the binding should contain a query (which contains a hash of the query string) and a meta_vars variable (which contains a hash of the environment, like SERVER_NAME) that you can access inside the rhtml files (and the servlet_request and servlet_response might be available too, but I'm not sure about them).

If that is not the case you can also try querying the CGI parameter ENV["QUERY_STRING"] and parse it, but this should only be as a last resort (and it might only work with CGI files).

like image 57
SztupY Avatar answered Jan 24 '23 16:01

SztupY


This is the solution:

(suppose the request is http://your.server.com/mypage.rhtml?foo=bar)

 <html>

    <body>

    This is my page (mypage.rhtml, served by webrick)

    <%
    # embedded ruby code

    servlet_request.query ["foo"] # this simply prints bar on console

    %>

    </body>

</html>
like image 35
cibercitizen1 Avatar answered Jan 24 '23 17:01

cibercitizen1