gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 08:14:56 25 4
gpt4 key购买 nike

我在模型类上有这段代码来添加 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com