How to localize a Rails plugin?

本小妞迷上赌 提交于 2020-01-02 09:29:42

问题


I'd like to translate the OpenIdAuthentication plugin into another language but I'd like not to change the plugin directly.

Here's the basic structure of the messages I want to translate:

module OpenIdAuthentication

  class Result
    ERROR_MESSAGES = {
      :missing      => "Sorry, the OpenID server couldn't be found",
      :invalid      => "Sorry, but this does not appear to be a valid OpenID",
      :canceled     => "OpenID verification was canceled",
      :failed       => "OpenID verification failed",
      :setup_needed => "OpenID verification needs setup"
    } 
  end

end

It is something possible to translate them without changing the plugin directly?

Thanks!


回答1:


You can simply overwrite OpenIdAuthentication::Result::ERROR_MESSAGES by redefining it at any time after the plugin loads.

You may do so through a different plugin (that loads after OpenIdAuthentication), or from a file required after the plugin loads (e.g. require lib/open_id_authentication_suppl.rb in environment.rb):

The code will essentially be a copy-paste job, as follows:

module OpenIdAuthentication

  class Result
    ERROR_MESSAGES = {
      :missing      => "<message in foreign language>",
      :invalid      => "<message in foreign language>",
      :canceled     => "<message in foreign language>",
      :failed       => "<message in foreign language>",
      :setup_needed => "<message in foreign language>"
    } 
  end

To integrate this with I18N-rails (built into Rails 2.2.2, available as a gem/plugin in previous versions), do:

  class I18NResultMessages
    def [](key)
      I18n.t(key, :scope => 'openidauthentication.errors.messages')
    end
  end

  class Result
    ERROR_MESSAGES = I18NResultMessages.new
  end

Then define and load your I18n yml file for openidauthentication.errors.messages's various locales on Rails startup, and don't forget to set your I18n.locale every time you start processing a controller action based on the logged-in user's locale.




回答2:


Copy that code into a file in /lib, then require it in environment.rb. It really is that easy.



来源:https://stackoverflow.com/questions/622250/how-to-localize-a-rails-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!