ruby-on-rails - 如何使用模块动态地将类方法添加到 Rails 模型

标签 ruby-on-rails ruby ruby-on-rails-3 metaprogramming meta-search

我在模型类上有这段代码来添加 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 doc .虽然它与您的问题没有直接关系,但 included 方法对于模型或 Controller (范围、辅助方法、过滤器等)以及 ActiveSupport::Concern 非常有用免费处理模块之间的依赖关系(无论是自由还是啤酒)。

关于ruby-on-rails - 如何使用模块动态地将类方法添加到 Rails 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20634651/

相关文章:

ruby-on-rails - 有人可以在 Rails 中用 Ruby 定义一个引擎吗?

ruby-on-rails - 我如何邀请用户(使用 devise_invitable)并在邀请过程中填充其他字段?

ruby-on-rails - Uncaught ReferenceError : Bloodhound is not defined

mysql - Action Controller::Connection 在使用 mysql 在 ruby​​ on rails 中创建应用程序时未建立

ruby-on-rails - 嵌套资源的 Rails 路线

ruby-on-rails - rails : unknown attribute error for derived class

ruby - ruby 2 中的 DateTime 减法?

ruby-on-rails - 未定义的方法 `group_by_day' - rails 3.2

ruby - 初始化方法的返回值

ruby-on-rails - Rails 中的两步身份验证