2010-11-23 4 views
1

컨트롤러가있어서 표준 방법을 포함하고 싶습니다. 레일 3 컨트롤러 내부에 중첩 모듈 포함

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 

답변

4

사용 extend 대신 당신의 ClassMethods에 대한 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 
예후 다 카츠에 의해이 문서는 왜 단지 확장 사용에 대한 자세한 세부 사항에 간다
+0

가 오버라이드 (override)보다 낫다 확장하려면 다음을 포함하십시오 : http://yehudakatz.com/2009/11/12/better-ruby-idioms/ – jergason

+0

그냥 'Base.extend MyModule :: ModelMethods'를 넣으시면됩니다.하지만 Base는 무엇을 의미합니까? 그것은'ActiveRecord :: Base'일까요? – Dex

+0

'Base'를 사용하여 간단하게 유지할 수있을 것이라고 생각했지만, 아마도 더 혼란 스럽습니다. ActiveRecord :: Base 사용법을 변경했습니다. –