Skip to content

Instantly share code, notes, and snippets.

@wojtha
Last active October 30, 2019 18:10
Show Gist options
  • Save wojtha/8868012a3a5f5cd5ab5dc0dd281ec7d8 to your computer and use it in GitHub Desktop.
Save wojtha/8868012a3a5f5cd5ab5dc0dd281ec7d8 to your computer and use it in GitHub Desktop.
An ActiveRecord::Finder implementation to extract query methods from the ApplicationRecord classes.
class ExampleFinder < ApplicationRecordFinder
finder_for ::Example
def list_examples_active_at(time)
active_at(time).all
end
def list_past_examples
where('end_at < ?', Time.current).all
end
def list_examples_older_than_month
where('end_at < ?', month_ago).all
end
private
finder_scope :active_at, ->(time) { where('start_at < :time AND :time < end_at', time: time) }
finder_scope :with_status, ->(status) { where(status: convert_status(status)) }
def month_ago
31.days.ago.beginning_of_day
end
def convert_status(status)
::Example.statuses.fetch(status, status)
end
end
# Example application finder
class ApplicationRecordFinder < ActiveRecord::Finder::Decorator
include ActiveRecord::Finder::Relation
include ActiveRecord::Finder::Model
include ActiveRecord::Finder::FinderScope
include ActiveRecord::Finder::QueryMethods
include ActiveRecord::Finder::Pagination
include ActiveRecord::Finder::StaticDispatcher
end
# Default finder base to inherit from.
module ActiveRecord
module Finder
class Base
include ActiveRecord::Finder::Model
include ActiveRecord::Finder::FinderScope
include ActiveRecord::Finder::QueryMethods
include ActiveRecord::Finder::StaticDispatcher
end
end
end
module ActiveRecord
module Finder
# Decorator class is an alternative to:
#
# `include ActiveRecord::Finder::Relation`
# `include ActiveRecord::Finder::QueryMethods`
#
# or more precisely:
#
# `include ActiveRecord::Finder::Relation`
# `include ActiveRecord::Finder::DelegateMissing`
#
class Decorator < SimpleDelegator
def initialize(relation)
super(relation.respond_to?(:to_relation) ? relation.to_relation : relation)
end
def relation
__getobj__
end
def default_scope
__getobj__.clone
end
def to_relation
__getobj__
end
def all
__getobj__
end
def new(*args)
self.class.new(*args)
end
end
end
end
module ActiveRecord
module Finder
module DelegateMissing
def method_missing(method_name, *args, &block)
if relation.respond_to?(method_name)
relation.public_send(method_name, *args, &block)
else
super
end
end
def respond_to_missing?(method_name, include_private = false)
relation.respond_to?(method_name, include_private) || super
end
end
end
end
module ActiveRecord
module Finder
module FinderScope
extend ActiveSupport::Concern
module ClassMethods
def finder_scope(name, body)
unless body.respond_to?(:call)
raise ArgumentError, "The scope body needs to be callable."
end
if respond_to?(name, true)
raise ArgumentError, "Creating scope :#{name}. Overwriting existing method #{self.name}.#{name}."
end
if body.respond_to?(:to_proc)
define_method(name) do |*args|
scope = instance_exec(*args, &body)
self.class.new(scope || default_scope)
end
else
define_method(name) do |*args|
scope = body.call(*args)
self.class.new(scope || default_scope)
end
end
protected name
end
end
end
end
end
module ActiveRecord
module Finder
module Model
extend ActiveSupport::Concern
include ActiveRecord::Finder::Relation
def initialize(relation = nil)
super(relation || self.class.model.all)
end
module ClassMethods
def finder_for(model)
@model = model
end
def model
@model or raise "Missing finder model. Please use `finder_for #{name}` to define the target ActiveRecord model"
end
end
end
end
end
module ActiveRecord
module Finder
module Pagination
def paginate(page, limit)
if limit.present?
relation.page(page).per(limit)
else
relation
end
end
end
end
end
module ActiveRecord
module Finder
# Module QueryMethods delegates all common ActiveRecord methods to stored relation.
# Methods listed in `QUERY_METHODS` and `SPAWN_METHODS` are decorated with finder class so it can use scopes.
# Methods listed in `FINDER_METHODS` and `CALCULATION_METHODS` returns relation directly.
#
module QueryMethods
# Curated list of methods from {ActiveRecord::FinderMethods}.
# Methods like `forty_two` or `second` or `second_to_last` has been omitted.
FINDER_METHODS = %i[
exists?
find
find_by
find_by!
first
first!
last
last!
take
take!
].freeze
# Curated list of methods from {ActiveRecord::QueryMethods} and {ActiveRecord::QueryMethods::WhereChain}
QUERY_METHODS = %i[
create_with
distinct
eager_load
extending
from
group
having
includes
joins
limit
lock
none
offset
or
order
preload
readonly
references
reorder
reverse_order
rewhere
select
uniq
unscope
where
not
].freeze
# List of methods from ActiveRecord::Batches
BATCHES_METHODS = %i[
find_each
find_in_batches
].freeze
# Curated list of {ActiveRecord::SpawnMethods}
SPAWN_METHODS = %i[
merge
except
only
].freeze
# Curated list of {ActiveRecord::Calculations}
CALCULATION_METHODS = %i[
average
calculate
count
ids
maximum
minimum
pluck
sum
].freeze
ENUMERATOR_METHODS = %i[
each
to_a
include?
].freeze
WRAPPED_METHODS = [*SPAWN_METHODS, *QUERY_METHODS].freeze
delegate *FINDER_METHODS, *BATCHES_METHODS, *CALCULATION_METHODS, *ENUMERATOR_METHODS, to: :relation
def method_missing(method_name, *args, &block)
if WRAPPED_METHODS.include?(method_name)
self.class.new(relation.public_send(method_name, *args, &block))
else
super
end
end
def respond_to_missing?(method_name, include_private = false)
WRAPPED_METHODS.include?(method_name) || super
end
end
end
end
module ActiveRecord
module Finder
module Relation
extend ActiveSupport::Concern
attr_reader :relation
def initialize(relation)
@relation = relation.respond_to?(:to_relation) ? relation.to_relation : relation
end
def default_scope
relation.clone
end
def to_relation
relation
end
def all
relation
end
def new(*args)
self.class.new(*args)
end
end
end
end
module ActiveRecord
module Finder
module RelationScope
extend ActiveSupport::Concern
module ClassMethods
# Adds a composable protected method for retrieving and querying objects.
#
# In contrary of ActiveRecord scope the Finder scopes intended to return a Finder object,
# so you can chain finder scopes easily.
#
# You have to call #relation after calling the last scope to return the {ActiveRecord::Relation}
# object or when you need to access the ActiveRecord query methods.
#
# You should call {#relation} or {#all} (or {ActiveRecord::Finder::Pagination#paginate})
#
# @example
#
# class TopicFinder
# include ActiveRecord::Finder::Model
# include ActiveRecord::Finder::RelationScope
#
# finder_for Topic
#
# def list_active_for_owned_by(owner)
# active.owned_by(owner).relation
# end
#
# def list_inactive_for_owned_by(owner)
# inactive.owned_by(owner).relation
# end
#
# def owned_by_user(owner)
# relation.where(owner_id: owner.id, owner_type: 'User')
# end
#
# def list_active_and_owned_by(owner)
# owned_by(owner).relation.where(archived: false)
# end
#
# relation_scope :active, -> { where(archived: false) }
# relation_scope :inactive, -> { where(archived: true) }
# relation_scope :owned_by, ->(owner) { where(owner_id: owner.id, owner_type: owner.class.to_s) }
#
# end
#
def relation_scope(name, body)
unless body.respond_to?(:call)
raise ArgumentError, "The scope body needs to be callable."
end
if respond_to?(name, true)
raise ArgumentError, "Creating scope :#{name}. Overwriting existing method #{self.name}.#{name}."
end
if body.respond_to?(:to_proc)
define_method(name) do |*args|
#scope = default_scope.scoping { instance_exec(*args, &body) }
scope = default_scope.scoping { relation.model.instance_exec(*args, &body) }
self.class.new(scope || default_scope)
end
else
define_method(name) do |*args|
scope = default_scope.scoping { body.call(*args) }
self.class.new(scope || default_scope)
end
end
protected name
end
end
end
end
end
module ActiveRecord
module Finder
module StaticDispatcher
extend ActiveSupport::Concern
module ClassMethods
def method_missing(method_name, *args, &block)
if instance_methods(false).include?(method_name.to_sym)
new.public_send(method_name, *args, &block)
else
super
end
end
def respond_to_missing?(method_name, _include_private)
instance_methods(false).include?(method_name.to_sym) || super
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment