Skip to content

Instantly share code, notes, and snippets.

@davetoxa
Last active April 12, 2023 08:49
Show Gist options
  • Save davetoxa/a65b5c897a2aa2d682df to your computer and use it in GitHub Desktop.
Save davetoxa/a65b5c897a2aa2d682df to your computer and use it in GitHub Desktop.
require 'active_record'
require 'open-uri'
require 'pg'
require 'minitest/autorun'
ActiveRecord::Base.establish_connection(
adapter: 'postgresql',
database: 'trgm',
host: 'localhost'
)
class Country < ActiveRecord::Base
def self.similar(query)
where('similarity(name, ?) > 0.3', query)
end
end
class CreateCountryTable < ActiveRecord::Migration[4.2]
def self.up
create_table :countries do |t|
t.string :name
end
data = JSON.load open("https://api.vk.com/api.php?oauth=1&method=database.getCountries&v=5.68&need_all=1&count=234")
data["response"]["items"].each do |country|
Country.create!(name: country["title"])
end
enable_extension "pg_trgm"
execute 'CREATE INDEX trgm_idx ON countries USING gist (name gist_trgm_ops);'
end
def self.down
drop_table :countries
end
end
CreateCountryTable.migrate(:up) unless ActiveRecord::Base.connection.table_exists? :countries
p "Country count: #{Country.count}"
Country.similar('мадивы').each do |country|
p country.name
end
describe Country do
it 'находит страну по точному названию' do
data = Country.similar 'Россия'
assert_equal data.count, 1
assert_equal data.first.name, 'Россия'
end
it 'находит страну с ошибкой в названии' do
data = Country.similar 'Росия'
assert_equal data.count, 1
assert_equal data.first.name, 'Россия'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment