Skip to content

Instantly share code, notes, and snippets.

@Pashio84
Last active March 1, 2024 07:37
Show Gist options
  • Save Pashio84/a4cae731bc3475a029cd9e6be3dc67d4 to your computer and use it in GitHub Desktop.
Save Pashio84/a4cae731bc3475a029cd9e6be3dc67d4 to your computer and use it in GitHub Desktop.
Partial match search excluding dashes and uppercase alphabet with Controller's concern on Ruby on Rails
module ActiveRecordSearchable
extend ActiveSupport::Concern
# Ref: https://www.fileformat.info/info/unicode/category/Pd/list.htm
DASH_CHARACTER_REGEX = /[\p{Pd}|ー−]/.freeze
class_methods do
def partial_match_search(table_name, column, query)
return all if query.blank?
normalized_query = normalize(query)
normalized_query.split(' ').inject(self) do |scope, word|
normalized_word = remove_dash(word).downcase
scope.where(
"REGEXP_REPLACE(LOWER(NORMALIZE(#{table_name}.#{column}, NFKC)),'[" +
"\u002D\u058A\u05BE\u1400\u1806\u2010\u2011\u2012\u2013\u2014\u2015\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u2E5D" +
"\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D\u10EADー−]'," +
"'', 'g') LIKE ?",
"%#{normalized_word}%"
)
end
end
end
def normalize(value)
value&.unicode_normalize(:nfkc)&.strip
end
def remove_dash(value)
value.gsub(DASH_CHARACTER_REGEX, '')
end
def replace_2bytes_dash(value)
value.gsub(DASH_CHARACTER_REGEX, '-')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment