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
According to the source code of erbhandler it runs the rhtml files this way:
So the binding should contain a
query
(which contains a hash of the query string) and ameta_vars
variable (which contains a hash of the environment, likeSERVER_NAME
) that you can access inside the rhtml files (and theservlet_request
andservlet_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).Browsing the documentation, it looks like you should have an
HTTPRequest
from which you can get the query string. You can then useparse_query
to get a name/value hash.Alternatively, it's possible that just calling
query()
will give you the hash directly... my Ruby-fu isn't quite up to it, but you might want to at least give it a try.You don't give much details, but I imagine you have a servlet to serve the files you will process with erb, and by default the web server serves any static file in a public directory.
This example is limited, when you go to /my always the same file is processed. Here you should construct the file path based on the request path. Here I said a important word: "request", everything you need is there.
To get the HTTP header parameters, use req[header_name]. To get the parameters in the query string, use req.query[param_name]. req is the HTTPRequest object passed to the servlet.
Once you have the parameter you need, you have to bind it to the template. In the example we pass the binding object from self (binding is defined in Kernel, and it represents the context where code is executing), so every local variable defined in the do_GET method would be available in the template. However, you can create your own binding for example passing a Proc object and pass it to the ERB processor when calling 'result'.
Everything together, your solution would look like:
This is the solution:
(suppose the request is http://your.server.com/mypage.rhtml?foo=bar)