Funny things and common gotchas to know and avoid - Get on Rails with Globalize! Part 7 of 8

posted: June 7th, 2007 · by: Sven

in: Globalization, Programming · tagged as: , , , , , , , ·  12 comments »

This article is part of the series “Get on Rails with Globalize!” and like the two last installments it’s a catch-all list: this time we’re going to point out some unexpected behaviours, problems and other funny things. Nothing world-shattering, just some things that you’ll probably want to be informed about so you don’t run into any problems.

  • I’m seeing lot’s of strange characters!
  • Weird Currency parsing results
  • Globalize WrongLanguageError on attribute read
  • Globalizes screws my RJS (or: my IE6)!

I’ll edit and complete this list as needed. If you’ve found any other common gotchas concerning Globalize, please drop me a note!

I’m seeing lot’s of strange characters!

… also known as: what’s with all these quotation marks?

While it’d probably be tempting to quote the classics “The sixties weren’t good to you, were they?” (Sarge, Cars) the real I18n superhero knows that you actually have a problem with your character encoding here. What you need to do is get your entire application stack (Ruby, Rails, your database, webserver …) talk utf-8.

Here are some resources that you might find useful:

Weird Currency parsing results

Beware that the Globalize Currency class is still somewhat biased when it comes to parsing numbers in that it will always use a dot “.” as a decimal separator regardless of what’s defined as the current Locale.

Also, there’s a bug that causes Globalize to parse a String like “1.9” to a Cents value of 109 Cents instead of 190 Cents like one would expect. So beware the results.

Both of these problems are fixed by this patch though (to the best of my knowledge this was first posted on the Rails I18n mailinglist ):


Locale.set('en-US')
p Globalize::Currency.parse('1.90') # => #<Globalize::Currency:0x3768078 @cents=190>
Locale.set('de-DE')
p Globalize::Currency.parse('1,90') # => #<Globalize::Currency:0x3767f10 @cents=190>

Globalize WrongLanguageError on attribute read

When you encounter this error you’re probably doing something like this:


p = Page.find(1) # returns an english page
Globalize::Locale.set 'fr-CH' # p is now the 'wrong' language
puts p.title # This throws WrongLanguageError.

This really should be:


Globalize::Locale.set 'fr-CH'
p = Page.find(1) # or: p.reload (if p is already there)
puts p.title

Alternatively, if you have Globalize extensions installed, you can use the switch_language method:


@page.switch_language(base_language.code) { @page.title }

Globalizes screws my RJS (or: my IE6)!

Not really.

But probably you’ve followed the instructions from Chad Fowlers book “Rails Receipes” (page 268) and adopted the following piece of code:


after_filter :set_charset
  def set_charset
    unless @headers["Content-Type"] =~ /charset/i
      @headers["Content-Type"] ||= ""
      @headers["Content-Type"] += "; charset=utf-8"
    end
  end
end

With this you’ll most probably end up delivering broken HTTP headers like this:

Content-Type: ;charset=utf-8

It has been reported that this successfully screws RJS and apparently leaves IE 6.0 choking, too.

You can easily get around this by changing the fourth line to:

@headers["Content-Type"] ||= "text/html"

Another, probably slightly better variant of the set_charset filter can be found here: Some common questions on getting started - Get on Rails with Globalize! Part 2 of 6

Others?

Of course this list can’t ever be complete. So, again: if you’ve found any other common gotchas concerning Globalize, please drop me a note!

Leave a comment

12 Comments

  1. Solomon White said March 8th, 2008 at 11:59 PM  

    If you have an existing model named Country, the default Globalize setup will clobber it, and every time you try to access your model, you will end up accessing Globalize::Country instead. As documented here , this is because of the default instructions to add include Globalize to your environment.rb.

    Two solutions are available – module-ize your model, or else leave off the include Globalize, and explicitly call Globalize::Locale (et al) throughout your application.

  2. Sven said March 12th, 2008 at 02:02 AM  

    Hey Solomon!

    Thanks for that headsup. That’s a useful tip! I’ve never ran into that, but for sure that’s something quite some people will need a solution for.

  3. Maciej Bi?as said May 12th, 2008 at 11:24 PM  

    Solomon, I guess you could also do something like that

    class Locale include Globalize::Locale end

    and now you wouldn’t have to type in Globalize:: all the time for accessing the Locale class.

    (someone, please correct me if I’m wrong)

  4. Onno Schuit said June 20th, 2008 at 04:53 PM  

    Hi,

    Excellent walkthrough!

    About the “Weird Currency parsing results”: the patch seems broken. Here’s the entire patched parse method:

    def self.parse(num)
      case
      when num.is_a?(String)
        raise ArgumentError, "Not an amount (#{num})" if num.delete("^0-9").empty?
        _sep=(Locale.active.currency_decimal_sep || Locale.active.decimal_sep) if Locale.active?
        _sep||='.'
        _dollars, _cents = num.delete("^0-9"+_sep).split(_sep, 2)
        if !_cents
          _cents = 0 
        elsif _cents.length==1 #FIX: 1.9 is 1.90 not 1.09!
          _cents=_cents+'0'
        end                                         
        Currency.new(_dollars.to_i * 100 + _cents.to_i)
      when num.is_a?(Numeric)
        Currency.new(num * 100)
      when num.is_a?(NilClass)
        Currency.na
      else
        raise ArgumentError, "Unrecognized object #{num.class.name} for Currency"
      end                 
    end
    

    Onno

  5. jack said January 23rd, 2011 at 11:25 AM  

    hanks for that headsup. That’s a useful tip! I’ve never ran into that, but for sure that’s something quite some people will need a solution for. cheap vps

  6. QQQ said February 7th, 2011 at 06:35 PM  

    Finally we kissed and the passion scale went sky high and I knew I was onto a good thing - sex was a certainty free porn videos. She never hesitated when I began to fondle her breasts and she willingly exposed them for me mobile porn. They were firm and I suspected a breast enhancement but said nothing - they still felt good and I was enjoying them and gradually working my way further south free porn tube. She was a step ahead of me and before I could completely undress her she moved on me atk hairy and I was suddenly having my pants pulled down and I was enjoying one of he best cock sucking hairy pussy experiences I had ever had. ABB728019394

  7. Ming2 said February 24th, 2011 at 07:41 AM  

    Combining RVM and Bundler yields a abundant accord of adaptability and consisency. pass4sure 70-235 This affords you the best of both worlds, pass4sure 70-431 arrangement akin abreast with the adeptness to install gems from git repositories, pass4sure 70-548 and in appliance gem loading based on appliance environment. pass4sure 70-569

  8. chat said March 31st, 2011 at 07:23 PM  

    Here is the best fix for rails gotchas:

    The following cleaned up the issue:

    Dependencies.loadoncepaths -= Dependencies.loadoncepaths.select{|path| \ path =~ %r(^#{File.dirname(FILE)}) }

  9. side sleeper pillow said April 22nd, 2011 at 07:03 AM  

    Nicely written article, Knowledgeable and informative post. I’m really glad I came my way along your site. Keep posting, I really like the whole topic. Thanks for sharing.

  10. Okey oyunu said May 12th, 2011 at 03:55 PM  

    Tüm dünya artik okey oyunu oynuyor. Yillardir bir çok oyun programi olmasina ragmen, içlerinden en güzeli olarak nitelendirebilecegimiz tek bir site göze çarpmaktadir. Diger tüm okey oyunu programlarinin aksine ücretsiz olmasi ve 3 boyutlu olarak hizmet vermesi mükemmel bir gelismedir. Sizlerde www.okey-oyunu.com adresinden bu essiz okey oyununu indirebilirsiniz. Kullanimi çok basit ve Türkçe dil seçenegi ile kolaylikla oyuna baslayabilirsiniz. Ister kendi ülkenizden, isterseniz dünyanin tüm farkli bölgelerinden dilediginiz oyun odalarini seçerek, oyuna hemen baslayabilirsiniz. Okey oyunu oynamak için artik arkadas bile aramaniza gerek kalmadan, bilgisayarinizdan 100 binlerce üye ile online olarak okey oyununu oynamanin zevkine varabilirsiniz.

  11. porno said May 22nd, 2011 at 01:29 PM  

    I do agree with all of the ideas you have presented in your post. They’re really convincing and will definitely work. Still, the posts are too short for newbies. Could you please extend them a bit from next time? Thanks for the post.

  12. porno said May 22nd, 2011 at 02:02 PM  

    good comment. thanks you friends.

    I’ve surfed the net more than three hours today, however, I haven’t found such useful information. Thanks a lot, it is really useful to me

Sorry, comments are closed for this article.

artweb design
Sven Fuchs
Grünberger Str. 65
10245 Berlin, Germany


http://www.artweb-design.de

Fon +49 (30) 47 98 69 96
Fax +49 (30) 47 98 69 97