Skip to content

Instantly share code, notes, and snippets.

@tokland
Last active March 5, 2024 06:22
Show Gist options
  • Star 26 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save tokland/1333253 to your computer and use it in GitHub Desktop.
Save tokland/1333253 to your computer and use it in GitHub Desktop.
Simple wrapper over arel
require 'active_record'
require 'arel'
# Ruby-like syntax in AR conditions using the underlying Arel layer (Rails >= 3.0).
#
# What you would usually write like this:
#
# User.where(["users.created_at > ? AND users.name LIKE ?", Date.yesterday, "Mary"])
#
# can now be written like this (note those parentheses required by the operators precedences):
#
# User.where((User[:created_at] > Date.yesterday) & (User[:name] =~ "Mary"))
#
module ArelExtensions
module ActiveRecord
module ClassMethods
delegate :[], :to => :arel_table
end
end
module Nodes
def self.included(base)
base.class_eval do
alias_method :&, :and
alias_method :|, :or
end
end
end
module Predications
def self.included(base)
base.class_eval do
alias_method :<, :lt
alias_method :<=, :lteq
alias_method :==, :eq
alias_method :>=, :gteq
alias_method :>, :gt
alias_method :=~, :matches
alias_method :^, :not_eq
alias_method :>>, :in
alias_method :<<, :not_in
end
end
end
end
ActiveRecord::Base.extend(ArelExtensions::ActiveRecord::ClassMethods)
Arel::Nodes::Node.send(:include, ArelExtensions::Nodes)
Arel::Predications.send(:include, ArelExtensions::Predications)
@sashaegorov
Copy link

Love it

@voltechs
Copy link

Same. No idea why this isn't a base part of Arel or at least Rails... it's quite clean. Nice work!

P.S. Any reason you didn't alias !=?

alias_method :"!=", :not_eq

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment