Skip to content

Instantly share code, notes, and snippets.

@brainwire
Forked from davetoxa/trgm.rb
Last active August 29, 2015 14:26
Show Gist options
  • Save brainwire/2de5b326da67e0aa8e6f to your computer and use it in GitHub Desktop.
Save brainwire/2de5b326da67e0aa8e6f 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',
username: 'postgres'
)
class Country < ActiveRecord::Base
def self.similar(query)
sql = %(
SELECT name, similarity(name, '#{query}') AS s_name
FROM countries WHERE name % '#{query}'
ORDER BY s_name desc
)
connection.query(sql)
end
end
class CreateCountryTable < ActiveRecord::Migration
def self.up
create_table :countries do |t|
t.string :name
end
data = JSON.load open("http://api.vk.com/method/database.getCountries?v=5.34&need_all=1&count=234&lang=ru")
data["response"]["items"].each do |country|
Country.create!(name: country["title"])
end
enable_extension "pg_trgm"
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.first + ": " + country.last
end
describe Country do
it 'находит страну по точному названию' do
data = Country.similar 'Россия'
assert_equal data.count, 1
assert_equal data.first[0], 'Россия'
assert_equal data.first[1], '1'
end
it 'находит страну с ошибкой в названии' do
data = Country.similar 'Росия'
assert_equal data.count, 1
assert_equal data.first[0], 'Россия'
assert data.first[1].to_f < 1
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment