【问题标题】:including Modules in controller包括控制器中的模块
【发布时间】:2009-08-06 07:08:27
【问题描述】:

我在 ruby​​ on rails 应用程序的 lib 目录中做了一个模块 就像

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

我在像这样的控制器中调用了它

include Selector

  select_for :organization, :submenu => :general

但我想在函数中调用它 即

 def select
  #Call the module here 
 end

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    让我们澄清一下:您在模块中定义了一个方法,并且您希望在实例方法中使用该方法。

    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
    

    我将稍微更改您的模块。这使用include 而不是extendextend 用于添加类方法,include 用于添加实例方法:

    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
    

    这会给你一个实例方法。如果你想要实例和类方法,你只需添加 ClassMethods 模块,并使用extend 而不是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
    

    这样就清楚了吗?在您的示例中,您将模块定义为Select,但在控制器中包含Selector...我只是在代码中使用了Select

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-09
      • 1970-01-01
      • 1970-01-01
      • 2017-05-20
      相关资源
      最近更新 更多