← Back to Upcase

Query Objects vs Concerns


(Justin Gordon) #1

In regards to QueryObjects in this article: http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/#comment-685500569, what’s a good argument for why this technique is better than having a concern that deals only with Query methods within a given model? Based on the example below, I prefer using a Concern. Furthermore, if we have 10 of these QueryClasses, that’s a lot more code than 10 methods in the concern.

Here’s the Code Climate article’s example

class AbandonedTrialQuery
  def initialize(relation = Account.scoped)
    @relation = relation
  end

  def find_each(&block)
    @relation.where(plan: nil, invites_count: 0).find_each(&block)
  end
end

And used like

AbandonedTrialQuery.new.find_each do |account|
  account.send_offer_for_support
end

Using a concern, the code would look like:

module Accounts::FinderMethods
  extend ActiveSupport::Concern
  module ClassMethods
    def self.abandondedTrials
      where(plan: nil, invites_count: 0)
    end
  end
end

and used like

Accounts.abandonedTrials.each do |account|
  account.send_offer_for_support
end

(Derek Prior) #2

Your use of a concern does not break up the class. It just moves the implementation of that class into several files. Additionally, the concern is now includable in several classes, are you accounting for that in your tests or are you comfortable ignoring that aspect of the code being in the concern?

We discussed extracting classes vs extracting modules in a development discussion. The notes are here: http://forum.thoughtbot.com/t/extracting-modules-vs-extracting-classes/1949/