Skip to content
This repository has been archived by the owner on Dec 16, 2024. It is now read-only.

Fix inflections according README #4

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,6 @@ gem 'httparty'

gem 'rspec', '~> 2.7.0'

group :development do
gem 'guard-rspec'
end
17 changes: 17 additions & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,27 @@ GEM
remote: http://rubygems.org/
specs:
diff-lcs (1.1.3)
ffi (1.0.11)
guard (1.1.1)
listen (>= 0.4.2)
thor (>= 0.14.6)
guard-rspec (1.1.0)
guard (>= 1.1)
httparty (0.8.0)
multi_json
multi_xml
listen (0.4.6)
rb-fchange (~> 0.0.5)
rb-fsevent (~> 0.9.1)
rb-inotify (~> 0.8.8)
multi_json (1.0.3)
multi_xml (0.4.1)
rake (0.9.2.2)
rb-fchange (0.0.5)
ffi
rb-fsevent (0.9.1)
rb-inotify (0.8.8)
ffi (>= 0.5.0)
rspec (2.7.0)
rspec-core (~> 2.7.0)
rspec-expectations (~> 2.7.0)
Expand All @@ -16,11 +31,13 @@ GEM
rspec-expectations (2.7.0)
diff-lcs (~> 1.1.2)
rspec-mocks (2.7.0)
thor (0.15.3)

PLATFORMS
ruby

DEPENDENCIES
guard-rspec
httparty
rake
rspec (~> 2.7.0)
24 changes: 24 additions & 0 deletions Guardfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# A sample Guardfile
# More info at https://github.com/guard/guard#readme

guard 'rspec', :version => 2 do
watch(%r{^spec/.+_spec\.rb$})
watch(%r{^lib/(.+)\.rb$}) { |m| "spec/lib/#{m[1]}_spec.rb" }
watch('spec/spec_helper.rb') { "spec" }

# Rails example
watch(%r{^app/(.+)\.rb$}) { |m| "spec/#{m[1]}_spec.rb" }
watch(%r{^app/(.*)(\.erb|\.haml)$}) { |m| "spec/#{m[1]}#{m[2]}_spec.rb" }
watch(%r{^app/controllers/(.+)_(controller)\.rb$}) { |m| ["spec/routing/#{m[1]}_routing_spec.rb", "spec/#{m[2]}s/#{m[1]}_#{m[2]}_spec.rb", "spec/acceptance/#{m[1]}_spec.rb"] }
watch(%r{^spec/support/(.+)\.rb$}) { "spec" }
watch('config/routes.rb') { "spec/routing" }
watch('app/controllers/application_controller.rb') { "spec/controllers" }

# Capybara request specs
watch(%r{^app/views/(.+)/.*\.(erb|haml)$}) { |m| "spec/requests/#{m[1]}_spec.rb" }

# Turnip features and steps
watch(%r{^spec/acceptance/(.+)\.feature$})
watch(%r{^spec/acceptance/steps/(.+)_steps\.rb$}) { |m| Dir[File.join("**/#{m[1]}.feature")][0] || 'spec/acceptance' }
end

29 changes: 14 additions & 15 deletions lib/yandex_inflect.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
module YandexInflect
# Число доступных вариантов склонений
INFLECTIONS_COUNT = 6

# Класс для получения данных с веб-сервиса Яндекса.
class Inflection
include HTTParty
Expand All @@ -21,55 +21,54 @@ def get(name)
options = {}
options[:query] = { :name => name }
inflections = self.class.get("/inflect.xml", options)

return inflections["inflections"]["inflection"]
return inflections["inflections"]["inflection"].map { |inflect| inflect['__content__'] }
end
end

# Кеширование успешных результатов запроса к веб-сервису
@@cache = {}

# Возвращает массив склонений (размером <tt>INFLECTIONS_COUNT</tt>) для слова <tt>word</tt>.
#
# Если слово не найдено в словаре, будет возвращен массив размерностью <tt>INFLECTIONS_COUNT</tt>,
# заполненный этим словом.
def self.inflections(word)
inflections = []
lookup = cache_lookup(word)

lookup = cache_lookup(word)
return lookup if lookup

get = Inflection.new.get(word) rescue nil # если поднято исключение, переходим к третьему варианту и не кешируем
case get
when Array then
when Array then
# Яндекс вернул массив склонений
inflections = get
# Кладем в кеш
cache_store(word, inflections)
when String then
when String then
# Яндекс вернул не массив склонений (слово не найдено в словаре),
# а только строку, забиваем этой строкой весь массив
# а только строку, забиваем этой строкой весь массив
inflections.fill(get, 0..INFLECTIONS_COUNT-1)
# Кладем в кеш
cache_store(word, inflections)
else
# Забиваем варианты склонений оригиналом
inflections.fill(word, 0..INFLECTIONS_COUNT-1)
end

inflections
end

# Очистить кеш
def self.clear_cache
@@cache.clear
end

private
def self.cache_lookup(word)
@@cache[word.to_s]
end

def self.cache_store(word, value)
@@cache[word.to_s] = value
end
Expand Down
28 changes: 17 additions & 11 deletions spec/yandex_inflect_spec.rb
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
# -*- encoding: utf-8 -*-
# -*- encoding: utf-8 -*-

require File.dirname(__FILE__) + '/spec_helper.rb'

describe YandexInflect do
before(:all) do
@sample_inflection = ["рубин", "рубина", "рубину", "рубин", "рубином", "рубине"]
@sample_inflection = ["рубин", "рубина", "рубину", "рубина", "рубином", "рубине"]
end

before(:each) do
@inflection = mock(:inflection)
YandexInflect::clear_cache
Expand Down Expand Up @@ -41,23 +41,23 @@
sample = ["рубин", "рубина", "рубину", "рубин", "рубином", "рубине"]
@inflection.stub!(:get).and_return(sample)
YandexInflect::Inflection.should_receive(:new).once.and_return(@inflection)

2.times { YandexInflect.inflections("рубин") }
end

it "should NOT cache unseccussful lookups" do
sample = nil
@inflection.stub!(:get).and_return(sample)
YandexInflect::Inflection.should_receive(:new).twice.and_return(@inflection)

2.times { YandexInflect.inflections("рубин") }
end

it "should allow to clear cache" do
sample = "рубин"
@inflection.stub!(:get).and_return(sample)
YandexInflect::Inflection.should_receive(:new).twice.and_return(@inflection)

YandexInflect.inflections("рубин")
YandexInflect.clear_cache
YandexInflect.inflections("рубин")
Expand All @@ -66,12 +66,18 @@

describe YandexInflect::Inflection do
before(:all) do
server_response = [{"__content__" => "рубин", "case" => "1"},
{"__content__" => "рубина", "case" => "2"},
{"__content__" => "рубину", "case" => "3"},
{"__content__" => "рубина", "case" => "4"},
{"__content__" => "рубином", "case" => "5"},
{"__content__" => "рубине", "case" => "6"}]
@sample_answer = {
"inflections"=>{"inflection"=>["рубин", "рубина", "рубину", "рубин", "рубином", "рубине"], "original"=>"рубин"}
"inflections"=>{"inflection"=> server_response, "original"=>"рубин"}
}
@sample_inflection = ["рубин", "рубина", "рубину", "рубин", "рубином", "рубине"]
@sample_inflection = ["рубин", "рубина", "рубину", "рубина", "рубином", "рубине"]
end

it "should get inflections for a word" do
YandexInflect::Inflection.should_receive(:get).and_return(@sample_answer)
YandexInflect::Inflection.new.get("рубин").should == @sample_inflection
Expand Down