我正在尝试编写一个 gem 来扩展 ActiveRecord 模型可用的方法。在这一点上,它非常简单,只包含 3 个文件,按照这个问题上列出的说明进行操作:Rails extension ActiveRecord::Base and using Railties to self-initilize。
my_gem.rb
require 'my_gem/railtie' if defined? ::Rails::Railtie
my_gem/railtie.rb
require 'my_gem/extensions'
module MyGem
class Railtie < ::Rails::Railtie
initializer "my_gem.extensions" do
ActiveSupport.on_load(:active_record) do
ActiveRecord::Base.send :include, Extensions
end
end
end
end
my_gem/extensions.rb
module MyGem
module Extensions
extend ActiveSupport::Concern
module ClassMethods
def in_the_past_x_days x = 14
where("#{self.table_name}.created_at > ?", x.days.ago)
.group("DATE(#{self.table_name}.created_at)")
end
end
end
end
但是,每当我尝试调用in_the_past_x_days
. 我错过了一些明显的东西吗?
更新
事实证明这是显而易见的,有关详细信息,请参阅答案。