From 92a603387c084f13a36bbf3844d89029bb73a753 Mon Sep 17 00:00:00 2001 From: sgrif Date: Fri, 17 May 2013 18:23:57 -0600 Subject: Add ability to specify how a class is converted to Arel predicate This adds the ability for rails apps or gems to have granular control over how a domain object is converted to sql. One simple use case would be to add support for Regexp. Another simple case would be something like the following: class DateRange < Struct.new(:start, :end) def include?(date) (start..end).cover?(date) end end class DateRangePredicate def call(attribute, range) attribute.in(range.start..range.end) end end ActiveRecord::PredicateBuilder.register_handler(DateRange, DateRangePredicate.new) More complex cases might include taking a currency object and converting it from EUR to USD before performing the query. By moving the existing handlers to this format, we were also able to nicely refactor a rather nasty method in PredicateBuilder. --- activerecord/test/cases/relation/predicate_builder_test.rb | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 activerecord/test/cases/relation/predicate_builder_test.rb (limited to 'activerecord/test/cases') diff --git a/activerecord/test/cases/relation/predicate_builder_test.rb b/activerecord/test/cases/relation/predicate_builder_test.rb new file mode 100644 index 0000000000..1c87f5c12e --- /dev/null +++ b/activerecord/test/cases/relation/predicate_builder_test.rb @@ -0,0 +1,14 @@ +require "cases/helper" +require 'models/topic' + +module ActiveRecord + class PredicateBuilderTest < ActiveRecord::TestCase + def test_registering_new_handlers + PredicateBuilder.register_handler(Regexp, proc do |column, value| + Arel::Nodes::InfixOperation.new('~', column, value.source) + end) + + assert_match %r{["`]topics["`].["`]title["`] ~ 'rails'}, Topic.where(title: /rails/).to_sql + end + end +end -- cgit v1.2.3