views:

37

answers:

2

How does the RoR localization engine take a .yaml file and produce such a nice API to access the localized text like: layout.side.title

What kind of class is it that you can just create a recursive style of property accessors?

+3  A: 

You have to look at the implementation. Basically, the keys are stored in a yaml file which are loaded via YAML.load this operation returns a hash. When you search for "layout.side.title" the string is normalized via normalize_key which return a array of symbols [:layout, :side, :title] and normalized_keys add the locale to it [:en, :layout, :side, :title]. Then each level of the hash of keys loaded previously is inspected to find if each corresponding member of the previously build array as a match in this inject loop

hellvinz
+1  A: 

I think that @hellvinz excellently answered first part of your question - how's the localization implemented.

But if you want to use dynamic nested accessors in a generic way and you have used i18n only as an example, then the OpenStruct might be a class for you.

x = OpenStruct.new
x.foo = 10
x.bar = OpenStruct.new
x.bar.blee = "hello"
x.bar.whatever = "xx"

puts x.foo          # => 10
puts x.bar.blee     # => "hello"
puts x.bar.whatever # => "xx"

It is implemented trough all mighty method_missing - for more info you can take a look into your ruby implementation (ostruct.rb)

pawien
oh ok so its reflection or meta programing. thanks!
Blankman
yup - every time you see some magic, there is almost always meta-programing spell behind it :-)
pawien