Created
March 3, 2022 22:16
-
-
Save phil-monroe/f63a5e23b68d546e1cdb9193883a9bee to your computer and use it in GitHub Desktop.
Quick way to de-boilerplate Arel usage for ActiveRecord relations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ActiveRecord::Base.include(Maven::ArelProxy::ActiveRecordExtension) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Maven::ArelProxy | |
attr_reader :model_class | |
def initialize(model_class) | |
@model_class = model_class | |
model_class.column_names.map do |col| | |
define_singleton_method(col) do | |
model_class.arel_table[col] | |
end | |
end | |
end | |
module ActiveRecordExtension | |
extend ActiveSupport::Concern | |
class_methods do | |
def arel_proxy | |
@_arel_proxy ||= ::Maven::ArelProxy.new(self) | |
end | |
def arel_where(&block) | |
where(arel_proxy.instance_eval(&block)) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment