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

查看:122
本文介绍了如何使用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. 如何从应用程序中调用模块中的方法?

谢谢.

推荐答案

到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天全站免登陆