代码之家  ›  专栏  ›  技术社区  ›  Dex

Rails 3,包括控制器内的嵌套模块

  •  1
  • Dex  · 技术社区  · 14 年前

    我有一个控制器,我想包括一些标准方法。

    class Main::UsersController < Main::BaseController
      include MyModule::ControllerMethods
    end
    

    uninitialized constanct MyModule::ClassMethods::InstanceMethods

    我的模块看起来是这样的,这也是错误的,最初是为模型设计的。最好的方法是什么,这样我就可以使用它的控制器以及?

    module MyModule
      def self.included(base)
        base.has_one  :example, :autosave => true
        base.before_create :make_awesome        
    
        base.extend ClassMethods
      end
    
      module ClassMethods
        ...
        include InstanceMethods
      end
    
      module InstanceMethods
         ...
      end
    
      module ControllerMethods
        ...
        # I want to include these in my controller
        def hello; end
        def world; end
      end
    
    end
    
    1 回复  |  直到 14 年前
        1
  •  4
  •   Petrik de Heus    14 年前

    使用 extend 而不是 include 为了你的课堂方法。还应拆分模型和控制器模块:

    module MyModule    
      module ModelMethods
        def acts_as_something
          send :has_one,  :example, :autosave => true
          send :before_create, :make_awesome  
          send :include, InstanceMethods
        end
        module InstanceMethods
          ...
        end
    
    
      end
    
      module ControllerMethods
        ...
        # I want to include these in my controller
        def hello; end
        def world; end
      end
    
    end
    
    ActiveRecord::Base.extend MyModule::ModelMethods
    

    然后,您的模型将如下所示:

    class Model < ActiveRecord::Base
      acts_as_something
    end