开发者

Rails 3 Including Nested Module Inside Controller

开发者 https://www.devze.com 2023-01-26 17:49 出处:网络
I have a controller that I\'d like to include some standard methods. class Main::UsersController < Main::BaseController

I have a controller that I'd like to include some standard methods.

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

uninitialized constanct MyModule::ClassMethods::InstanceMethods

My module looks like this, which is also wrong, and was originally meant for a model. What's the best way to do it so that I can use it with a controller as well?

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


Use extend instead of include for your ClassMethods. You should also split your model and controller modules:

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

Your Model would then look like this:

class Model < ActiveRecord::Base
  acts_as_something
end
0

精彩评论

暂无评论...
验证码 换一张
取 消