如何使用 Ruby on Rails 3 创建和使用模块? [英] How to create and use a module using Ruby on Rails 3?

查看:33
本文介绍了如何使用 Ruby on Rails 3 创建和使用模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Ruby on Rails 3,我想在模块中移动一些自定义和共享代码.

I am using Ruby on Rails 3 and I would like to move some custom and shared code in a module.

  1. 我应该使用什么语法来编写模块代码?
  2. 我必须在应用程序的哪个文件夹中放置模块文件?
  3. 我必须如何将该模块包含在一个或多个控制器类中?
  4. 在我的应用程序中的任何位置使用自定义模块时,我还需要采取哪些其他措施?
  5. 如何从我的应用程序调用模块中的方法?

提前致谢.

推荐答案

To 1. 一个模块被创建/打开简单地说:

To 1. A module is created/opened by simply saying:

module MyModule
  def first_module_method
  end
end

到 2. lib 文件夹.如果您想在 lib 文件夹中组织您的模块,您可以将它们自己放入模块中.例如,如果您想要一个子文件夹 super_modules,您的模块将被定义如下:

To 2. The lib folder. If you want to organize your modules in the lib folder, you can put them into modules themselves. For example, if you wanted a subfolder super_modules your modules would be defined as follows:

module SuperModules
  module MyModule
    def first_module_method
    end
  end
end

到 3./5.当在类中包含模块时,您可以简单地调用模块方法,就像它们在类中定义一样:

To 3./5. When including the module in a class you can simply call the modules methods as if they were defined within the class:

class MyClass
  include MyModule
  def some_method
    first_module_method #calls module method
  end
end

到 4.首先,请确保您的应用程序的每个类都确实需要您的模块.如果不是,则只在需要的地方包含它才有意义,以免使不需要它的类膨胀.如果您真的希望该模块无处不在,请查看应用程序中类的类层次结构.你想要所有型号的模块吗?你可以打开 ActiveRecord::Base 并在那里添加你的模块.

To 4. Frst, make sure that your module is really needed in every class of your application. If it isn't it makes sense to only include it where it is need so as not to bloat the classes that don't need it anyways. If you really want the module everywhere, include look at the class hierarchy of your classes in the app. Do you want the module in all models? You could open ActiveRecord::Base and add add your module there.

这篇关于如何使用 Ruby on Rails 3 创建和使用模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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