How to use DRY methods in two different classes?

I am using Ruby on Rails 3.2.2, and I would like to get / link objects using the "definition" / "filter" attribute value for these related objects. That is, at this time I am using the following code:

class Article < ActiveRecord::Base
  def self.search_by_title(search)
    where('articles.title LIKE ?', "%#{search}%")
  end
end

class ArticleAssociation < ActiveRecord::Base
  def self.search_by_article_title(search)
    joins(:article).where('articles.title LIKE ?', "%#{search}%")
  end
end

In the above code, the sentence is where('articles.title LIKE ?', "%#{search}%")repeated twice, so I thought that it could be improved using the DRY principle: is it possible to use the method Article.search_by_titledirectly in the method ArticleAssociation.search_by_article_title?


Typical use cases:

  • ArticleAssociation.search_by_article_title("Sample string")
  • Article.search_by_title("Sample string")
+5
source share
2 answers

Unless you completely change the structure of the code, no.

, , , . , , , . , . , , , , , .

, , , , :

class Article < ActiveRecord::Base
  SEARCH_BY_TITLE=lambda {|obj, search| obj.where('articles.title LIKE ?', "%#{search}%")}
  def self.search_by_title(search)
    SEARCH_BY_TITLE.call(self, search)
  end
end

class ArticleAssociation < ActiveRecord::Base
  def self.search_by_article_title(search)
    Article::SEARCH_BY_TITLE.call(joins(:article),search)
  end
end

lambda , where . .

. , , lambdas, , Ruby. , .

+2

OP , 3- , :

module Listable
  extend ActiveSupport::Concern

  module ClassMethods
    # Search a listable module search in properties (or related) tables
    def search_from_properties(string)
      return where({}) if string.blank?
      associations = self.reflect_on_all_associations.map(&:name) &
        [:property, :properties, :supplier, :suppliers, :address]
      s = "%#{string}%"
      associations.inject(self, :includes).where(
        ((Address[:base] =~ s) | (Address[:city] =~ s)) |
        ((Property[:owner] =~ s) | (Property[:cif] =~ s)) | 
        ((Supplier[:cups] =~ s) | (Supplier[:contract] =~ s))
      )
    end
  end
end

:

class Property < ActiveRecord::Base
  include Listable
end

. , (, joins). , AR.

+1

All Articles