Setting a cooking from an eruby .rhtml file

X

Xeno Campanoli

I also tried inserting the cookings at an intermediate page that
redirects, and I'm having no luck with that either, though I can simply
use the plain CGI object to do it inside of a <% %> pair.
 
M

Martin Boese

I assume you call the eruby program as the cgi handler from your webserver
(apache?).

The eruby program doesn't have a 'feature' to modify http headers that it
outputs with -Mc if I am not mistaken.

An easy solution would be to write a small wrapper:

---------------- myeruby.rb ---------------------
require 'erb'
require 'cgi'

class ErbSpace
def set_cookie(a_cookie)
@cookie ||= []
@cookie << a_cookie
end

def get_cookies
@cookie || false
end

def get_binding
binding
end
end

template = ERB.new(File.read(ARGV[0]))
es = ErbSpace.new
content = template.result(es.get_binding)

cgi = CGI.new
cgi.out('cookie'=>es.get_cookies) { content }
-----------

Now I have a set_cookie method in the erb template that I can call anywhere in
the script:

------------- test.rhtml ------------------
<% set_cookie(CGI::Cookie::new('username', 'someone')) %>


<html>

<%= "A ruby string".reverse %>


</html>
<% set_cookie(CGI::Cookie::new('another_cookie', 'test')) %>
-----------

----------- See if it works: ---------------

$ ruby myeruby.rb test.rhtml
Content-Type: text/html
Content-Length: 36
Set-Cookie: username=someone; path=
Set-Cookie: another_cookie=test; path=




<html>

gnirts ybur A


</html>
-------------------

Now just change your webserver to call myeruby.rb instead of eruby for .rhtml
files. Also this provides you a good starting point to add more methods to
ErbSpace if you need.

See also:

ri CGI
ri CGI::Cookie
ri erb

Martin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top