views:

913

answers:

3

I have a page which uses the UTF-8 character set, however the characters are mangled on the page, I think this is just a matter of setting a header "Content-Type: text/html; charset=utf-8" ... I know how to do this in PHP, simply place the following at the top of the page.

<?php header("Content-Type: text/html; charset=utf-8"); ?>

Is there a way to do this in ruby? Can you place a header at the top of a page, like that?


update: Jun 29, 1:20p PST

I'm not using this as part of a rails application. It is for an embedded browser page in a stand-alone application, I can use Javascript and/or Ruby to create dynamic pages.

+1  A: 

Are you using Ruby on Rails?

request.headers["Content-Type"] # => "text/plain"

Or maybe Ruby's CGI library?

http://www.ruby-doc.org/stdlib/libdoc/cgi/rdoc/classes/CGI.html#M000098

alltom
+1  A: 

If you're using Rails, you want:

response.content_type = Mime::HTML
response.charset      = "utf-8"

You could also try to set the headers directly:

response.headers["Content-Type"] = "text/html; charset=utf-8"

If you're using Rack, you want to set the header using the second element of the tuple:

class MyRackApp
  def call(env)
    response = []
    # do stuff with env, populating response
    # response is [status_code, headers, body]
    response[1]["Content-Type"] = "text/html; charset=utf-8"
    response
  end
end

If you're using raw CGI (I would definitely recommend Rack over cgi.rb):

header("text/html; charset=utf-8")
Yehuda Katz
Thanks for the three views. I used the "cgi" library. (It was quick-n-dirty)
null
A: 

I'm not sure how to answer this directly without learning more about how you're generating the page, but I might suggest you look into some of the lightweight non-Rails web frameworks for Ruby. There are many and they make things like this easy.

For example, Rack has an easy-to-use hash for Headers to send to the browser. Likewise in Camping you can just do something like @headers['Content-Type'] = 'text/css'

Eli