Skip to content

Instantly share code, notes, and snippets.

@2called-chaos
Created April 3, 2020 00:07
Show Gist options
  • Save 2called-chaos/64f64fc7fb35959fbf68f6018494a698 to your computer and use it in GitHub Desktop.
Save 2called-chaos/64f64fc7fb35959fbf68f6018494a698 to your computer and use it in GitHub Desktop.
Custom number converter example (fuzzily)
class Product < ApplicationRecord
fuzzily_searchable :search_name, class_name: "ProductTrigram"
def search_name
term = [name, name_origin, *search_terms.try(:split, ",")].join(" ")
term = FuzzilyStringConverter.convert_in_string(term)
term.split(" ").uniq.join(" ")
end
def saved_change_to_search_name?
saved_change_to_name? || saved_change_to_name_origin? || saved_change_to_search_terms?
end
end
class SearchController < ApplicationController
def index
query = FuzzilyStringConverter.convert_in_string(params[:query])
ids = Product.find_by_fuzzy_search_name(query, limit: 50).map(&:id)
# …
end
end
class FuzzilyStringConverter
def self.convert_in_string input
deromanize(input).gsub(/\d/) {|num| utf8_mapping[num.to_i] }
end
def self.deromanize input
input.gsub(/\w+/) {|el| roman_to_latin_mapping[el.upcase] || el }
end
def self.utf8_mapping
{
0 => "aaa",
1 => "bbb",
2 => "ccc",
3 => "ddd",
4 => "eee",
5 => "fff",
6 => "ggg",
7 => "hhh",
8 => "iii",
9 => "jjj",
}
end
def self.roman_to_latin_mapping
{
"I" => 1,
"II" => 2,
"III" => 3,
"IV" => 4,
"V" => 5,
"VI" => 6,
"VII" => 7,
"VIII" => 8,
"IX" => 9,
"X" => 10,
"XI" => 11,
"XII" => 12,
"XIII" => 13,
"XIV" => 14,
"XV" => 15,
"XVI" => 16,
"XVII" => 17,
"XVIII" => 18,
"XIX" => 19,
"XX" => 20,
"XXI" => 21,
"XXII" => 22,
"XXIII" => 23,
"XXIV" => 24,
"XXV" => 25,
"XXVI" => 26,
"XXVII" => 27,
"XXVIII" => 28,
"XXIX" => 29,
"XXX" => 30,
"XXXI" => 31,
"XXXII" => 32,
"XXXIII" => 33,
"XXXIV" => 34,
"XXXV" => 35,
"XXXVI" => 36,
"XXXVII" => 37,
"XXXVIII" => 38,
"XXXIX" => 39,
"XL" => 40,
"XLI" => 41,
"XLII" => 42,
"XLIII" => 43,
"XLIV" => 44,
"XLV" => 45,
"XLVI" => 46,
"XLVII" => 47,
"XLVIII" => 48,
"XLIX" => 49,
"L" => 50,
"LI" => 51,
"LII" => 52,
"LIII" => 53,
"LIV" => 54,
"LV" => 55,
"LVI" => 56,
"LVII" => 57,
"LVIII" => 58,
"LIX" => 59,
"LX" => 60,
"LXI" => 61,
"LXII" => 62,
"LXIII" => 63,
"LXIV" => 64,
"LXV" => 65,
"LXVI" => 66,
"LXVII" => 67,
"LXVIII" => 68,
"LXIX" => 69,
"LXX" => 70,
"LXXI" => 71,
"LXXII" => 72,
"LXXIII" => 73,
"LXXIV" => 74,
"LXXV" => 75,
"LXXVI" => 76,
"LXXVII" => 77,
"LXXVIII" => 78,
"LXXIX" => 79,
"LXXX" => 80,
"LXXXI" => 81,
"LXXXII" => 82,
"LXXXIII" => 83,
"LXXXIV" => 84,
"LXXXV" => 85,
"LXXXVI" => 86,
"LXXXVII" => 87,
"LXXXVIII" => 88,
"LXXXIX" => 89,
"XC" => 90,
"XCI" => 91,
"XCII" => 92,
"XCIII" => 93,
"XCIV" => 94,
"XCV" => 95,
"XCVI" => 96,
"XCVII" => 97,
"XCVIII" => 98,
"XCIX" => 99,
"C" => 100,
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment