Ruby on rails 如何使用模块向Rails模型动态添加类方法

Ruby on rails 如何使用模块向Rails模型动态添加类方法,ruby-on-rails,ruby,ruby-on-rails-3,metaprogramming,meta-search,Ruby On Rails,Ruby,Ruby On Rails 3,Metaprogramming,Meta Search,我在模型类上有此代码,用于添加搜索方法,供meta\u searchgem使用: 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 类模型 self

我在模型类上有此代码,用于添加搜索方法,供
meta\u 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
类模型
self.def在某天(日期)的某时某时某时某时创建

其中(“created_at您需要添加一个
类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

请参阅。尽管它与您的问题没有直接关系,但包含的
方法对模型或控制器(作用域、帮助器方法、过滤器等)非常有用,另外
ActiveSupport::Concern
可以免费处理模块之间的依赖关系(如freedom和beer).

您是否
包括元搜索?
?谢谢!对我来说非常有用。
undefined method `created_at_lteq_end_of_day' for #<ActiveRecord::Relation:0x007fcd3cdb0e28>
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
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