我在模型类上有这段代码,用于添加meta_search
gem:使用的搜索方法
class Model
self.def created_at_lteq_at_end_of_day(date)
where("created_at <= ?", DateTime.strptime(date, '%d/%m/%Y').end_of_day)
end
search_methods :created_at_lteq_at_end_of_day
end
此代码将搜索方法添加到日期字段。现在,需要将此搜索方法添加到其他类和其他字段中。为了实现这一点,创建了这个模块:
lib/meta_search/extended_search_methods.rb
module MetaSearch
module ExtendedSearchMethods
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def add_search_by_end_of_day(field, format)
method_name = "#{field}_lteq_end_of_day"
define_method method_name do |date|
where("#{field} <= ?", DateTime.strptime(date, format).end_of_day)
end
search_methods method_name
end
end
end
end
class Model
include MetaSearch::ExtendedSearchMethods
add_search_by_end_of_day :created_at, '%d/%m/%Y'
end
添加模块后,此错误开始上升:
undefined method `created_at_lteq_end_of_day' for #<ActiveRecord::Relation:0x007fcd3cdb0e28>
其他解决方案:
将define_method
更改为define_singleton_method
ActiveSupport提供了一种非常惯用且很酷的方法,ActiveSupport::Concern
:
module Whatever
extend ActiveSupport::Concern
module ClassMethods
def say_hello_to(to)
puts "Hello #{to}"
end
end
end
class YourModel
include Whatever
say_hello_to "someone"
end
请参阅API文档。虽然included
方法与您的问题没有直接关系,但它对模型或控制器(作用域、辅助方法、过滤器等)非常有用,而且ActiveSupport::Concern
可以免费处理模块之间的依赖关系(无论是在freedom中还是在beer中)。
您需要添加一个class << self
,以便在单例类中工作。
module Library
module Methods
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def add_foo
class << self
define_method "foo" do
puts "Foo!"
end #define_method
end #class << self
end #add_foo
end #ClassMethods
end #Methods
end #Library
class Test
include Library::Methods
add_foo
end
puts Test.foo