在Rails 3中扩展模块 [英] Extend a module in Rails 3

查看:74
本文介绍了在Rails 3中扩展模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一个函数available_translations,该函数列出了我为应用程序所做的到I18n模块的翻译.

I want to define a function available_translations which lists the translations I have made for my application into the I18n module.

我尝试将以下内容放入文件lib/i18n.rb中,但是当我尝试从Rails控制台使用它时,它不起作用:

I tried putting the following into the file lib/i18n.rb, but it doesn't work when I try to use it from the rails console:

module I18n
  # Return the translations available for this application.
  def self.available_translations
    languages = []
    Dir.glob(Rails.root.to_s + '/config/locales/*.yml') do |filename|
      if md = filename.match #^.+/(\w+).yml$#
        languages << md[1]
      end
    end
    languages
  end
end

控制台:

ruby-1.9.2-p290 :003 > require Rails.root.to_s + '/lib/i18n.rb'
=> false
ruby-1.9.2-p290 :004 > I18n.available_translations
NoMethodError: undefined method `available_translations' for I18n:Module
...

除了解决我的具体问题外,我将非常高兴学习Ruby on Rails中的整个模块的工作原理,因为它仍然使我感到困惑,因此,我非常感谢与文档或源代码的链接 .

Besides solving my concrete problem, I would be very pleased to learn how this whole module thing in Ruby on Rails works because it still confuses me, so I would appreciate links to the docs or source code very much.

推荐答案

以下任一方法都可以解决您的问题:

Either of these will solve your problem:

  • 将代码移至config/initializers/i18n.rb,或
  • 从config/application.rb中获取文件,或
  • 否则为您的班级命名(以触发自动加载)

自动加载不会加载lib/i18n.rb中的代码,因为已经加载了I18n名称,因此您可以自己加载它或更改类名(和文件名),以便新名称将触发自动加载行为.

The code in lib/i18n.rb wil not be loaded by autoload since I18n name will be already loaded, so either you load it yourself or change the class name (and file name) so the new name will trigger autoload behavior.

这篇关于在Rails 3中扩展模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆