How to create and use a module using Ruby on Rails 3?

前端 未结 2 1720
北海茫月
北海茫月 2020-12-07 07:29

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

  1. What syntax should I use to write the module code?
  2. In w
2条回答
  •  一向
    一向 (楼主)
    2020-12-07 08:12

    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.

提交回复
热议问题