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

时间:2010-11-23 11:34:21

标签: ruby-on-rails ruby

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

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 个答案:

答案 0 :(得分:4)

使用extend代替include进行ClassMethods。您还应拆分模型和控制器模块:

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
相关问题