I am trying to add some special methods to ActiveRecord. I want to add *_after and *_before for each date field of the model so that I can do something like this:
User.created_at_after(DateTime.now - 3.days).created_at_before(DateTime.now)
I executed the Rails solution described here extending ActiveRecord :: Base , but when I start the rails console and try to call methods, I get an undefined method error.
Here is my code:
# config/initializers/active_record_date_extension.rb require "active_record_date_extension" # lib/active_record_date_extension.rb module ActiveRecordDateExtension extend ActiveSupport::Concern included do |base| base.columns_hash.each do |column_name,column| if ["datetime","date"].include? column.type base.define_method("#{column_name}_after") do |date| where("#{column_name} > ?", date) end base.define_method("#{column_name}_before") do |date| where("#{column_name} < ?", date) end end end end end Rails.application.eager_load! ActiveRecord::Base.descendants.each do |model| model.send(:include, ActiveRecordDateExtension) end
What am I doing wrong?
ruby ruby-on-rails activerecord ruby-on-rails-4 metaprogramming
Simon soriano
source share