我創建了包含在類中的模塊。在模塊中,我試圖定義一個方法,它是沒有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
是的,哪來的'show'方法? – 2012-07-24 23:53:16
define_method(self.name.downcase.gsub('filter','').to_sym){self} – chris 2012-07-25 00:03:55