Answer the question
In order to leave comments, you need to log in
What is the correct way to generate dynamic methods in Rails?
I can't figure out how to make define_method work:
Mongoid,
localized_fields are used
Everything is fine, but in some questions it is terribly inconvenient to work:
For example, to explicitly get the Russian version of the name field - I need to knock on name_translations[:ru] - which is wildly inconvenient,
Or else engage in constant locale switching, like this:
curr = I18.locale
I18n.locale = :en
Model.name
I18n.locale = curr
module My::Localized
module ClassMethods
def params_localized
self.attribute_names.each do |value|
if self.fields[value].localized?
I18n.available_locales.each do |loc|
define_method("#{value}__#{loc}") do
self["#{value}_translations"][loc]
end
end
end
end
end
end
end
Answer the question
In order to leave comments, you need to log in
module My::Localized
def self.params_localized
end
end
module My::Localized
def params_localized
end
end
def with_locale(locale)
old_locale = I18n.locale
I18n.locale = locale
begin
yield
ensure
I18n.locale = old_locale
end
end
with_locale :ru do
# ...
end
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question