Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monkey patch module method

I want to alter I18n.translate method in existing project.

require 'I18n'
module I18n
  alias_method :old_translate, :translate
  def translate(*args)
    old_translate(*args) + 'blabla'
  end
  alias_method :t, :translate
end

This generates:

Uncaught exception: Missing helper file helpers/I18n.rb

What I do wrong and where I should put this code?

like image 677
Jonas Avatar asked Dec 18 '12 07:12

Jonas


1 Answers

config/locales/en.yml:

en:
  wtfblabla: hello

test.rb:

require 'i18n'
module I18n
  class<< self
    alias_method :old_translate, :translate
    def translate(*args)
      old_translate(*args) + 'blabla'
    end
    alias_method :t, :translate
  end
end

I18n.load_path += p(Dir[File.join(File.dirname(__FILE__), 'config', 'locales', '*.yml').to_s])

p I18n.t "wtfblabla"

output:

["./config/locales/en.yml"]

"helloblabla"

like image 64
nurettin Avatar answered Nov 15 '22 07:11

nurettin