Commit 87b51c59 authored by Hiroyuki Sato's avatar Hiroyuki Sato

Move the logic to a concern

parent 866aab7f
......@@ -5,6 +5,7 @@ class User < ActiveRecord::Base
include Gitlab::ConfigHelper
include Gitlab::CurrentSettings
include Gitlab::SQL::Pattern
include Avatarable
include Referable
include Sortable
......@@ -303,7 +304,7 @@ class User < ActiveRecord::Base
# Returns an ActiveRecord::Relation.
def search(query)
table = arel_table
pattern = Gitlab::SQL::Pattern.new(query).to_sql
pattern = User.to_pattern(query)
order = <<~SQL
CASE
......
module Gitlab
module SQL
class Pattern
MIN_CHARS_FOR_PARTIAL_MATCHING = 3
attr_reader :query
module Pattern
extend ActiveSupport::Concern
def initialize(query)
@query = query
end
MIN_CHARS_FOR_PARTIAL_MATCHING = 3
def to_sql
if exact_matching?
sanitized_query
else
"%#{sanitized_query}%"
class_methods do
def to_pattern(query)
if exact_matching?(query)
sanitize_sql_like(query)
else
"%#{sanitize_sql_like(query)}%"
end
end
end
def exact_matching?
!partial_matching?
end
def partial_matching?
@query.length >= MIN_CHARS_FOR_PARTIAL_MATCHING
end
def exact_matching?(query)
query.length < MIN_CHARS_FOR_PARTIAL_MATCHING
end
def sanitized_query
# Note: ActiveRecord::Base.sanitize_sql_like is a protected method
ActiveRecord::Base.__send__(:sanitize_sql_like, query)
def partial_matching?(query)
query.length >= MIN_CHARS_FOR_PARTIAL_MATCHING
end
end
end
end
......
require 'spec_helper'
describe Gitlab::SQL::Pattern do
describe '#to_sql' do
subject(:to_sql) { described_class.new(query).to_sql }
describe '#to_pattern' do
subject(:to_pattern) { User.to_pattern(query) }
context 'when a query is shorter than 3 chars' do
let(:query) { '12' }
it 'returns exact matching pattern' do
expect(to_sql).to eq('12')
expect(to_pattern).to eq('12')
end
end
......@@ -16,7 +16,7 @@ describe Gitlab::SQL::Pattern do
let(:query) { '_2' }
it 'returns sanitized exact matching pattern' do
expect(to_sql).to eq('\_2')
expect(to_pattern).to eq('\_2')
end
end
......@@ -24,7 +24,7 @@ describe Gitlab::SQL::Pattern do
let(:query) { '123' }
it 'returns partial matching pattern' do
expect(to_sql).to eq('%123%')
expect(to_pattern).to eq('%123%')
end
end
......@@ -32,7 +32,7 @@ describe Gitlab::SQL::Pattern do
let(:query) { '_23' }
it 'returns partial matching pattern' do
expect(to_sql).to eq('%\_23%')
expect(to_pattern).to eq('%\_23%')
end
end
......@@ -40,7 +40,7 @@ describe Gitlab::SQL::Pattern do
let(:query) { '1234' }
it 'returns partial matching pattern' do
expect(to_sql).to eq('%1234%')
expect(to_pattern).to eq('%1234%')
end
end
......@@ -48,7 +48,7 @@ describe Gitlab::SQL::Pattern do
let(:query) { '_234' }
it 'returns sanitized partial matching pattern' do
expect(to_sql).to eq('%\_234%')
expect(to_pattern).to eq('%\_234%')
end
end
end
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment