This is a worthy solution, but not the best solution. When you create a module on ActiveSupport::Concern
, you can wrap a module called ClassMethods
inside your problem, and any module that includes your problem will be automatically expanded using the ClassMethods
module.
Then the best solution would be:
module Searchable extend ActiveSupport::Concern module ClassMethods def search(search) if search where('name LIKE ?', "%#{search}%") else scoped end end end end
This (IMO) more clearly expresses your intention: placing a class of a class in a class.
While your approach works, the included
method is best used when you need to call methods in the calling class. For example, you can insist that your Searchable
objects have a name
attribute with db support, as shown below. The method included
adding validator presence
to the calling class, and the methods that you use to extend the class, separated clearly.
module Searchable extend ActiveSupport::Concern def self.included(base) base.send :validates_presence_of, :name end module ClassMethods def search(search) if search where('name LIKE ?', "%#{search}%") else scoped end end end end
AndyV source share