V
V
Vladislav Shchekoldin2015-02-22 16:19:00
MongoDB
Vladislav Shchekoldin, 2015-02-22 16:19:00

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

Which, by the way, does not guarantee that there will be a Russian version of the field. Basically, it's more fun.
So far, the number of localized fields is finite, in principle, you can simply do
def name__ru and def name__ru(value)
However, I would like to achieve a slightly different behavior: We look at the model, and for each field we see with the localized parameter? = true
we declare a seter and a geter according to the rules "#{name}__#{loc}".
I actually wrote the following small module (for now, only a getter).
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

But I can’t figure out how to make it work when connected to the Model ...
Now it doesn’t work at all ...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
vsuhachev, 2015-02-23
@vsuhachev

module My::Localized
  def self.params_localized
  end
end

and then include My::Localized
Either
module My::Localized
  def params_localized
  end
end

and then extend My::Localized
Or Concerns
PS:
A bit off topic, your code with changing locales can be made more convenient
def with_locale(locale)
  old_locale = I18n.locale
  I18n.locale = locale
  begin
    yield
  ensure
    I18n.locale = old_locale
  end
end

Usage:
with_locale :ru do
  # ...
end

A
Alexey, 2015-02-22
@fuCtor

How do you connect the module and how should the method be called then? And so you can use Concerns .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question