… That you will probably end up creating yourself …
After over 12 years of working with Ruby on Rails on multiple different codebases, I’ve some common themes. This is my list of patterns or types of objects you will see in Rails applications.
1. Query Objects.
ActiveRecord provides the scope macro which allows us to define queries related to that model. However, for larger, more complex queries that span multiple models, scopes can often lead to a patchwork of distributed logic. To address this, I prefer to build stand alone a Query object. I usually place this in a separate folder: `app/queries’. The following is an example of query object:
A simple base query object:
module Kenglish QueryResult = Struct.new(:data, :meta) class Query class << self def result(*args) new(*args).result end end attr_reader :params, :relation def initialize(params, relation) @params = params @relation = relation end def build_result(data, meta) QueryResult.new(data, meta) end end end