Setting a cooking from an eruby .rhtml file

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.

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

On Thursday 10 July 2008 03:30:49 Xeno Campanoli wrote:

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.