2009-08-06 17 views
6

Zrobiłem moduł w katalogu lib w Ruby on zastosowania szyn jej jaktym moduły w kontrolerze

module Select 

    def self.included(base) 
    base.extend ClassMethods 
    end 

module ClassMethods 

    def select_for(object_name, options={}) 

     #does some operation 
     self.send(:include, Selector::InstanceMethods) 
    end 
    end 

zadzwoniłem to w kontrolerze jak

include Selector 

    select_for :organization, :submenu => :general 

ale chcę zadzwonić to w funkcji tj

def select 
    #Call the module here 
end 

Odpowiedz

14

Rozjaśnijmy: Y masz metodę zdefiniowaną w module i chcesz, aby ta metoda była używana w metodzie instancji.

class MyController < ApplicationController 
    include Select 

    # You used to call this in the class scope, we're going to move it to 
    # An instance scope. 
    # 
    # select_for :organization, :submenu => :general 

    def show # Or any action 
    # Now we're using this inside an instance method. 
    # 
    select_for :organization, :submenu => :general 

    end 

end 

Zamierzam nieco zmienić moduł. To używa include zamiast extend. extend jest dodanie metody klasy, a include go do dodawania metody instancji:

module Select 

    def self.included(base) 
    base.class_eval do 
     include InstanceMethods 
    end 
    end 

    module InstanceMethods 

    def select_for(object_name, options={}) 
     # Does some operation 
     self.send(:include, Selector::InstanceMethods) 
    end 

    end 

end 

To daje metodę instancji. Jeśli chcesz obie metody instancji i klasy, wystarczy dodać moduł ClassMethods i używać extend zamiast include:

module Select 

    def self.included(base) 
    base.class_eval do 
     include InstanceMethods 
     extend ClassMethods 
    end 
    end 

    module InstanceMethods 

    def select_for(object_name, options={}) 
     # Does some operation 
     self.send(:include, Selector::InstanceMethods) 
    end 

    end 

    module ClassMethods 

    def a_class_method 
    end 

    end 

end 

Czy to jasne rzeczy? W twoim przykładzie zdefiniowałeś moduł jako Select, ale włączyłeś Selector w swoim kontrolerze ... Właśnie użyłem Select w moim kodzie.