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.