2012-07-24 90 views
1

我創建了包含在類中的模塊。在模塊中,我試圖定義一個方法,它是沒有Filter的類名稱的下降版本。所以ShowFilter會有一個名爲show的方法返回類Show。我得到「NoMethodError: 未定義的方法`秀」爲ShowFilter:類」在具有變量名稱的模塊中定義類方法

module Filters 

    module Base 

    module ClassMethods 

     @@filters = {} 

     def filter name, &block 
     @@filters[name] = block 
     end 

     def run query = {} 
     query.each do |name, value| 
      @@filters[name.to_sym].call(value) unless @@filters[name.to_sym].nil? 
     end 
     self 
     end 

     def self.extended(base) 
     name = base.class.name.gsub(/filter/i, '') 
     define_method(name.downcase.to_sym) { Kernel.const_get name } 
     end 


    end 

    def self.included base 
     base.extend ClassMethods 
    end 

    end 

end 


class ShowFilter 
    include Filters::Base 

    filter :name do |name| 
     self.show.where(:name => name) 
    end 

end 

編輯:使用

class ShowController < ApplicationController 
    def index 
    ShowFilter.run params[:query] 
    end 
end 
+0

是的,哪來的'show'方法? – 2012-07-24 23:53:16

+0

define_method(self.name.downcase.gsub('filter','').to_sym){self} – chris 2012-07-25 00:03:55

回答

3

當你定義Filters::Base::ClassMethods的例子,它在這方面評估自我所以你最終定義的方法是ClassMethods.classmethods(因爲gsub不會做任何事情)。

就像你在基地打入了包括鉤,要在ClassMethods使用擴展:

module Filters 
    module Base 
    module ClassMethods 

     @@filters = {} 

     def filter name, &block 
     @@filters[name] = block 
     end 

     def run query = {} 
     query.each do |name, value| 
      @@filters[name.to_sym].call(value) unless @@filters[name.to_sym].nil? 
     end 
     Object.const_get(self.to_s.gsub('Filter', '')) 
     end 

     def self.extended(base) 
     define_method(base.to_s.downcase.gsub('filter', '').to_sym) do 
      Object.const_get(self.to_s.gsub('Filter', '')) 
     end 
     end 
    end 

    def self.included base 
     base.extend ClassMethods 
    end 
    end 
end 
class ShowFilter 
    include Filters::Base 

    filter :title do |title| 
    self.show.where(:title => title) 
    end 
end 
+0

我嘗試了你的建議,新代碼是在原來的問題。我仍然收到錯誤。我正在嘗試爲mongoid模型定義一個過濾器DSL。我希望能夠在幾個過濾器類中包含基本過濾器模塊,並通過名稱「show」訪問該過濾器的模型,而不是像「model」那樣的通用模型。 – chris 2012-07-25 00:28:23

+0

好吧我更新了我的代碼。我仍然不確定它應該返回什麼。它是'self.filter'嗎?或者它可能是一個名爲'self.downcase.gsub('filter','')'' – Chris 2012-07-25 00:41:20

+0

的模型。抱歉,我可能在工作時編輯了我的代碼,請再次看看它返回的內容,它應該更清晰。感謝您看這個!基本上ShowFilter應該有一個類方法show,它返回類Show(不是實例,而是類本身)。而一個BugsFilter類會有一個方法錯誤返回類Bugs。 – chris 2012-07-25 00:45:28

相關問題