Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to translate model in Ruby class/module namespace?

I have a model Products::Car. How can I translate its attributes?

I have already tried this:

activerecord:    models:     products:       car: "Автомобиль"   attributes:     products:       car:         owner: "Владелец" 

And this:

activerecord:    models:     products_car: "Автомобиль"   attributes:     products_car:       owner: "Владелец" 

But if I try to use Products::Car.model_name.human it still says "Car". My other translations work well, and the language is set to :ru.

like image 941
Alex Avatar asked Oct 07 '11 21:10

Alex


People also ask

How do you use a namespace in Ruby?

The namespace in Ruby is defined by prefixing the keyword module in front of the namespace name. The name of namespaces and classes always start from a capital letter. You can access the sub members of double with the help of :: operator. It is also called the constant resolution operator.

What is the difference between a class and a module Ruby?

What is the difference between a class and a module? Modules are collections of methods and constants. They cannot generate instances. Classes may generate instances (objects), and have per-instance state (instance variables).

How do I use a module in Ruby?

The method definitions look similar, too: Module methods are defined just like class methods. As with class methods, you call a module method by preceding its name with the module's name and a period, and you reference a constant using the module name and two colons.

Can you instantiate a module in Ruby?

You can define and access instance variables within a module's instance methods, but you can't actually instantiate a module.


1 Answers

I have checked 'model_name.human' source code and found 'i18n_key' method. I have tried this:

irb(main):006:0> Products::Car.model_name.i18n_key => :"products/car" 

Then I changed my yml file to this:

activerecord:       models:     products/car: "Автомобиль"      attributes:     products/car:       owner: "Владелец" 

and it works!

EDIT:

For further reference: the i18n_key is set in the initializer of ActiveModel::Name https://github.com/rails/rails/blob/375a4143cf5caeb6159b338be824903edfd62836/activemodel/lib/active_model/naming.rb#L147

and it is simply based on

MyClass.name.underscore 
like image 112
Alex Avatar answered Sep 23 '22 11:09

Alex