I have a small logic, that alows I18n 'inplace translation' with AJAX, directly on the page. Therefore I want to intercept I18n.translate
My investigations brought me to this - nice and clean looking - logic: based on this SO Answer (Method Wrapping) and some "how could it work" trial and errors
module I18n
extend Module.new {
old_translate=I18n.method(:translate)
define_method(:translate) do |*args|
InplaceTrans.translate(old_translate,*args)
end
alias :t :translate
}
end
and
module InplaceTrans
extend Module.new {
def translate(old_translate,*args)
Translator.new.translate(old_translate, *args)
end
}
end
the Translator.new.translate()
is just a Trick, so i dont have to restart rails server when developing
All above is working fine and stable, but i don't realy know what I am doing ...
Question(s):
Is this a valid (and clean) approach?
What does the extend Model.new { ... }
do?
what is the difference to extend Model.new DO ... END
? (seems to do nothing in my case)
EDIT: answerd my self: according to DO/END vs {} and at end of question:
And why does InplaceTrans.translate
inside I18n.newly_defined_method()
resolve to my anonymous module.translate
according to this:
Creates a new anonymous module. If a block is given, it is passed the module object, and the block is evaluated in the context of this module using module_eval.
So it works, but i realy would like to know why!
(RoR 1.9.3,3.2)
EDIT: partial answer
extend Module.new {}
evolves to extend(Module.new {})
whereas
extend Module.new do/end
evolves to extend(Module.new) do/end
so with do/end the block is bound to result of extend. if you want to use do/end you must use braces:
extend(Module.new do/end)
same as extend Module.new {}