如何使用 RubyonRails 3创建和使用模块?

我正在使用 RubyonRails 3,我想在一个模块中移动一些自定义和共享的代码。

  1. 我应该使用什么语法来编写模块代码?
  2. 我必须在应用程序的哪个文件夹中放置模块文件?
  3. 如何将该模块包含在一个或多个控制器类中?
  4. 如果有的话,我还需要在应用程序的任何地方使用自定义模块执行哪些操作?
  5. 如何从应用程序调用模块中的方法?

先谢谢你。

79401 次浏览

A>1. You can use the same syntax as any other ruby class. For instance, I'm defining a VehicleClassifer module which is going to use the classify_vehicle method to classify a vehicle based on the number of wheels it receives as an input.

module VehicleClassifer
def classify_vehicle(number_of_wheels)
VehicleType.where("number_of_wheels = ?", number_of_wheels)
end
end

A>2. Modules are usually stored in the /lib folder.

questions 3,4,5 have more or less the same answer. you can use

class SomeController < ApplicationController
include VehicleClassfier


def index
classify_vehicle(4)
end
end

in the class you're using the module and you will have access to all the module's methods.

Also, In case you need to use a module through out your app, you can include it in your application controller.

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

module MyModule
def first_module_method
end
end

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

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

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.