2010-11-23 31 views
1

私はいくつかの標準的な方法を含めるコントローラを持っています。Rails 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の代わりに、あなたのクラスメソッドのため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

イェフダカッツによるこの記事では、単に拡張使用して上書きするよりも優れている理由について、より詳細にに行きます以下を拡張してください:http://yehudakatz.com/2009/11/12/better-ruby-idioms/ – jergason

+0

ちょうど不思議なことに、あなたは 'Base.extend MyModule :: ModelMethods'を入れますが、' Base'はそれに関係しています。それは 'ActiveRecord :: Base'でしょうか? – Dex

+0

私は 'Base'を使って単純にしておくと思っていましたが、おそらくもっと混乱します。 ActiveRecord :: Baseを使用する答えを変更しました。 –

関連する問題