0

I have a subject from an email that comes in to my rails 3 application like this :

I trying to then save this subject in my database(mongodb) as a string field using mail.subject but i get error 'String not valid UTF-8' ??

Anyone know how i solve this ?

thanks alot rick

rick
  • 463
  • 5
  • 23

1 Answers1

0

You haven't shown any sample code, but it looks like the subject returned isn't UTF-8 encoded, but your database is. Try using force_encoding before saving the subject.

mail.subject.force_encoding("UTF-8")

EDIT:

For ruby 1.8.7, shamelessly stolen from String.force_encoding() in Ruby 1.8.7 (or Rails 2.x)

require 'iconv'
class String
  def to_my_utf8
    ::Iconv.conv('UTF-8//IGNORE', 'UTF-8', self + ' ')[0..-2]
  end
end

And then...

mail.subject.to_my_utf8
Community
  • 1
  • 1
ghoppe
  • 21,452
  • 3
  • 30
  • 21
  • hi i get this error message when i try your suggestion any ideas ? undefined method `force_encoding' for "FW: Save almost \2432,000 on a luxury Alaskan yacht holiday!":String – rick May 10 '11 at 20:04
  • @rick Oh, sorry. You must be using Ruby 1.8 then? You'll have to use `iconv`. See this question for help on that: http://stackoverflow.com/questions/4583924/string-force-encoding-in-ruby-1-8-7-or-rails-2-x – ghoppe May 10 '11 at 20:11
  • thanks for the help that sort of works but no for say Japanese characters for example when i receive this text in a subject of a mail (パンを食べない。) "I will not eat bread"‏ and access the mail.subject or mail.subject.to_my_utf8 it comers out like this "(\e$B%Q%s$r?)$Y$J$$!#\e(B) \"I will not eat bread\"" any ideas how to display / save this properly ? thank a lot – rick May 10 '11 at 21:21