title: How to dynamically add class methods to Rails Models using module
body: <p>I have this code on model class to add search methods to be used by <code>meta_search</code> gem:</p>
  
  <pre><code>class Model
  
    self.def created_at_lteq_at_end_of_day(date)
       where("created_at &lt;= ?", DateTime.strptime(date, '%d/%m/%Y').end_of_day)
    end
  
    search_methods :created_at_lteq_at_end_of_day
  end
  </code></pre>
  
  <p>This code add search methods to date field. 
  Now, is needed to add this search method to other classes and with others fields. 
  To achieve this, this module was created:</p>
  
  <p><strong>lib/meta_search/extended_search_methods.rb</strong></p>
  
  <pre><code>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} &lt;= ?", 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
  </code></pre>
  
  <p>After add the module, this errors starts to rise:</p>
  
  <pre><code>undefined method `created_at_lteq_end_of_day' for #&lt;ActiveRecord::Relation:0x007fcd3cdb0e28&gt;
  </code></pre>
  
  <p><strong>Other solution:</strong></p>
  
  <p>change <code>define_method</code> to <code>define_singleton_method</code></p>