multi-lingual fields in mongodb

556 views
Skip to first unread message

rmossuk

unread,
Jun 30, 2010, 8:37:47 AM6/30/10
to MongoMapper
hi all


I have a category collection and each category has a array of hashes
containing attributes names and units to create a inout form with, to
add a product of that category.

for example category car fields - {name : length, unit : mm}, {name :
weight, unit : kg}.

Problem is i would this site to be multi-lingual and therefore need to
store the field names per language.

I could put them inline :

for example category car fields - {en-name : length, cn-name : .....,
de-name : ....., unit : mm}

Is there a better way ?

Not sure if this is best way as i want to be able to pass a docuement
of names needing to be translated to the translator for all field
names for all categories, so storing this way i would have to grab all
then put into another docuement then translate and inset new
translated naes back!!!

Any help or ideas ?


Thanks
rick

Carlos Paramio

unread,
Jun 30, 2010, 3:50:30 PM6/30/10
to MongoMapper
I personally store the localized attributes as a hash (ex: name : {:en
=> 'english name', :es => 'spanish name'} ).

To help with the manipulation of these kind of attributes, I defined a
custom type for them:

class LocalizedString < HashWithIndifferentAccess
def self.from_mongo(value)
LocalizedString.new(value || {})
end

def available_locales
symbolize_keys.keys
end

def in_current_locale
self[I18n.locale]
end

def in_current_locale=(value)
self[I18n.locale] = value
end
end


I'm using the I18n class from Rails.

This way, on the MongoMapper::Document, I just have to declare each
translatable attribute to use this class as its type, like:

key :name, LocalizedString


The only thing I don't like of this method is that the attribute
doesn't get marked as dirty when I change one of the translations like
in:

object.name[:en] = "new english name"
object.name_changed? # returns false

A different approximation would be to save the localized attributes on
separated documents. Take a look at how it works the dm-is-localizable
gem for DataMapper, for example.

Carlos Paramio
Reply all
Reply to author
Forward
0 new messages