morpher_inflect 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2008 Yaroslav Markin
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.rdoc ADDED
@@ -0,0 +1,39 @@
1
+ = MorpherInflect
2
+
3
+ Morpher.ru webservice client (provides Russian language pluralization)
4
+ based on yandex_inflect gem code for Yandex.Inflect webservice client
5
+
6
+ Клиент сервиса Morpher (склонение слов на русском языке)
7
+
8
+ * http://morpher.ru
9
+
10
+ Основан на yandex_inflect, имеет аналогичный API
11
+ Сервис условно бесплатен (см. сайт автора), имеет ограничения. В отличие
12
+ от яндекс.инфлект - склоняет и неодушевленные существительные
13
+ (еду в "Ростов", а не в "Ростова").
14
+
15
+ == Установка
16
+
17
+ Установка в качестве gem (с GemCutter):
18
+
19
+ gem install morpher_inflect
20
+
21
+ == Использование
22
+
23
+ > MorpherInflect.inflections("рубин")
24
+ => ["рубин", "рубина", "рубину", "рубин", "рубином", "рубине"]
25
+ > MorpherInflect.inflections("ЭтогоСловаНетВСловаре")
26
+ => ["ЭтогоСловаНетВСловаре", "ЭтогоСловаНетВСловаре", "ЭтогоСловаНетВСловаре",
27
+ "ЭтогоСловаНетВСловаре", "ЭтогоСловаНетВСловаре", "ЭтогоСловаНетВСловаре"]
28
+
29
+ Если во время общения с веб-сервисом произошла ошибка, возвращается массив, забитый оригинальной строкой.
30
+
31
+ Успешные ответы от веб-сервиса кешируются, кеш можно очистить с помощью
32
+
33
+ > MorpherInflect.clear_cache
34
+
35
+ == Авторы
36
+
37
+ * оригинальный yandex_inflect: Ярослав Маркин <yaroslav@markin.net>
38
+ * адаптация под morpher: Алексей Трофименко <codesnik@gmail.com>
39
+
data/Rakefile ADDED
@@ -0,0 +1,55 @@
1
+ require 'rubygems'
2
+ require 'rake/gempackagetask'
3
+ require 'spec/rake/spectask'
4
+ require 'rubygems/specification'
5
+ require 'date'
6
+
7
+ GEM = "morpher_inflect"
8
+ GEM_VERSION = "0.0.1"
9
+ AUTHOR = "Alexey Trofimenko"
10
+ EMAIL = "codesnik@gmail.com"
11
+ HOMEPAGE = "http://github.com/codesnik/morpher_inflect/"
12
+ SUMMARY = "Morpher.ru webservice client (Russian language inflection)"
13
+
14
+ spec = Gem::Specification.new do |s|
15
+ s.name = GEM
16
+ s.version = GEM_VERSION
17
+ s.platform = Gem::Platform::RUBY
18
+ s.has_rdoc = true
19
+ s.extra_rdoc_files = ["README.rdoc", "LICENSE", 'TODO']
20
+ s.summary = SUMMARY
21
+ s.description = s.summary
22
+ s.author = AUTHOR
23
+ s.email = EMAIL
24
+ s.homepage = HOMEPAGE
25
+
26
+ # Uncomment this to add a dependency
27
+ s.add_dependency "httparty"
28
+
29
+ s.require_path = 'lib'
30
+ s.autorequire = GEM
31
+ s.files = %w(LICENSE README.rdoc Rakefile TODO init.rb) + Dir.glob("{lib,spec}/**/*")
32
+ end
33
+
34
+ Rake::GemPackageTask.new(spec) do |pkg|
35
+ pkg.gem_spec = spec
36
+ end
37
+
38
+ task :default => :spec
39
+ desc "Run specs"
40
+ Spec::Rake::SpecTask.new do |t|
41
+ t.spec_files = FileList['spec/**/*_spec.rb']
42
+ t.spec_opts = %w(-fs --color)
43
+ end
44
+
45
+ desc "install the gem locally"
46
+ task :install => [:package] do
47
+ sh %{sudo gem install pkg/#{GEM}-#{GEM_VERSION}}
48
+ end
49
+
50
+ desc "create a gemspec file"
51
+ task :make_spec do
52
+ File.open("#{GEM}.gemspec", "w") do |file|
53
+ file.puts spec.to_ruby
54
+ end
55
+ end
data/TODO ADDED
File without changes
data/init.rb ADDED
@@ -0,0 +1,3 @@
1
+ # Rails plugin init
2
+ require 'morpher_inflect'
3
+
@@ -0,0 +1,9 @@
1
+ module MorpherInflect
2
+ module VERSION #:nodoc:
3
+ MAJOR = 0
4
+ MINOR = 0
5
+ TINY = 1
6
+
7
+ STRING = [MAJOR, MINOR, TINY].join('.')
8
+ end
9
+ end
@@ -0,0 +1,75 @@
1
+ $KCODE = 'u'
2
+
3
+ $:.unshift(File.dirname(__FILE__)) unless
4
+ $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))
5
+
6
+ require 'rubygems'
7
+ require 'httparty'
8
+
9
+ module MorpherInflect
10
+ # Число доступных вариантов склонений
11
+ INFLECTIONS_COUNT = 6
12
+
13
+ # Класс для получения данных с веб-сервиса Морфера.
14
+ class Inflection
15
+ include HTTParty
16
+ base_uri 'http://morpher.ru/Webservices/Morpher.asmx/'
17
+
18
+ # Получить склонения для имени <tt>name</tt>
19
+ def get(text)
20
+ options = {}
21
+ options[:query] = { :s => text }
22
+ inflections = self.class.get("/GetForms", options)
23
+
24
+ return inflections["ArrayOfString"]["string"]
25
+ end
26
+ end
27
+
28
+ # Кеширование успешных результатов запроса к веб-сервису
29
+ @@cache = {}
30
+
31
+ # Возвращает массив склонений (размером <tt>INFLECTIONS_COUNT</tt>) для слова <tt>word</tt>.
32
+ #
33
+ # Если слово не найдено в словаре, будет возвращен массив размерностью <tt>INFLECTIONS_COUNT</tt>,
34
+ # заполненный этим словом.
35
+ def self.inflections(word)
36
+ inflections = []
37
+
38
+ lookup = cache_lookup(word)
39
+ return lookup if lookup
40
+
41
+ get = Inflection.new.get(word) rescue nil # если поднято исключение, переходим к третьему варианту и не кешируем
42
+ case get
43
+ when Array then
44
+ # Морфер вернул массив склонений
45
+ inflections = [word] + get
46
+ # Кладем в кеш
47
+ cache_store(word, inflections)
48
+ when String then
49
+ # Морфер вернул не массив склонений (слово не найдено в словаре),
50
+ # а только строку. Скорее всего это ошибка. Забиваем оригинальным словом
51
+ inflections.fill(word, 0..INFLECTIONS_COUNT-1)
52
+ # Кладем в кеш
53
+ cache_store(word, inflections)
54
+ else
55
+ # Забиваем варианты склонений оригиналом
56
+ inflections.fill(word, 0..INFLECTIONS_COUNT-1)
57
+ end
58
+
59
+ inflections
60
+ end
61
+
62
+ # Очистить кеш
63
+ def self.clear_cache
64
+ @@cache.clear
65
+ end
66
+
67
+ private
68
+ def self.cache_lookup(word)
69
+ @@cache[word.to_s]
70
+ end
71
+
72
+ def self.cache_store(word, value)
73
+ @@cache[word.to_s] = value
74
+ end
75
+ end
@@ -0,0 +1,78 @@
1
+ require File.dirname(__FILE__) + '/spec_helper.rb'
2
+
3
+ describe MorpherInflect do
4
+ before(:all) do
5
+ @sample_inflection_response = ["рубина", "рубину", "рубин", "рубином", "рубине"]
6
+ @sample_inflection = ["рубин"] + @sample_inflection_response
7
+ end
8
+
9
+ before(:each) do
10
+ @inflection = mock(:inflection)
11
+ MorpherInflect::clear_cache
12
+ end
13
+
14
+ it "should return an array of inflections when webservice returns an array" do
15
+ @inflection.stub!(:get).and_return(@sample_inflection_response)
16
+ MorpherInflect::Inflection.should_receive(:new).and_return(@inflection)
17
+ MorpherInflect.inflections("рубин").should == @sample_inflection
18
+ end
19
+
20
+ it "should return an array filled with identical strings when webservice returns an error string" do
21
+ @inflection.stub!(:get).and_return("Программа не может просклонять это словосочетание.")
22
+ MorpherInflect::Inflection.should_receive(:new).and_return(@inflection)
23
+ MorpherInflect.inflections("рубин").should == %w(рубин рубин рубин рубин рубин рубин)
24
+ end
25
+
26
+ it "should return an array filled with identical strings of original word when webservice does not return anything meaningful or throws an exception" do
27
+ @inflection.stub!(:get).and_return(nil)
28
+ MorpherInflect::Inflection.should_receive(:new).and_return(@inflection)
29
+ MorpherInflect.inflections("рубин").should == %w(рубин рубин рубин рубин рубин рубин)
30
+ end
31
+ end
32
+
33
+ describe MorpherInflect, "with caching" do
34
+ before(:each) do
35
+ @inflection = mock(:inflection)
36
+ MorpherInflect::clear_cache
37
+ end
38
+
39
+ it "should cache successful lookups" do
40
+ sample = ["рубина", "рубину", "рубин", "рубином", "рубине"]
41
+ @inflection.stub!(:get).and_return(sample)
42
+ MorpherInflect::Inflection.should_receive(:new).once.and_return(@inflection)
43
+
44
+ 2.times { MorpherInflect.inflections("рубин") }
45
+ end
46
+
47
+ it "should NOT cache unseccussful lookups" do
48
+ sample = nil
49
+ @inflection.stub!(:get).and_return(sample)
50
+ MorpherInflect::Inflection.should_receive(:new).twice.and_return(@inflection)
51
+
52
+ 2.times { MorpherInflect.inflections("рубин") }
53
+ end
54
+
55
+ it "should allow to clear cache" do
56
+ sample = "рубин"
57
+ @inflection.stub!(:get).and_return(sample)
58
+ MorpherInflect::Inflection.should_receive(:new).twice.and_return(@inflection)
59
+
60
+ MorpherInflect.inflections("рубин")
61
+ MorpherInflect.clear_cache
62
+ MorpherInflect.inflections("рубин")
63
+ end
64
+ end
65
+
66
+ describe MorpherInflect::Inflection do
67
+ before(:all) do
68
+ @sample_answer = {
69
+ "ArrayOfString"=>{"string"=>["рубина", "рубину", "рубин", "рубином", "рубине"]}
70
+ }
71
+ @sample_inflection = ["рубина", "рубину", "рубин", "рубином", "рубине"]
72
+ end
73
+
74
+ it "should get inflections for a word" do
75
+ MorpherInflect::Inflection.should_receive(:get).and_return(@sample_answer)
76
+ MorpherInflect::Inflection.new.get("рубин").should == @sample_inflection
77
+ end
78
+ end
data/spec/spec.opts ADDED
@@ -0,0 +1,2 @@
1
+ --colour
2
+ --format specdoc
@@ -0,0 +1,10 @@
1
+ begin
2
+ require 'spec'
3
+ rescue LoadError
4
+ require 'rubygems'
5
+ gem 'rspec'
6
+ require 'spec'
7
+ end
8
+
9
+ $:.unshift(File.dirname(__FILE__) + '/../lib')
10
+ require 'morpher_inflect'
metadata ADDED
@@ -0,0 +1,75 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: morpher_inflect
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Alexey Trofimenko
8
+ autorequire: morpher_inflect
9
+ bindir: bin
10
+ cert_chain: []
11
+
12
+ date: 2009-11-23 00:00:00 +03:00
13
+ default_executable:
14
+ dependencies:
15
+ - !ruby/object:Gem::Dependency
16
+ name: httparty
17
+ type: :runtime
18
+ version_requirement:
19
+ version_requirements: !ruby/object:Gem::Requirement
20
+ requirements:
21
+ - - ">="
22
+ - !ruby/object:Gem::Version
23
+ version: "0"
24
+ version:
25
+ description: Morpher.ru webservice client (Russian language inflection)
26
+ email: codesnik@gmail.com
27
+ executables: []
28
+
29
+ extensions: []
30
+
31
+ extra_rdoc_files:
32
+ - README.rdoc
33
+ - LICENSE
34
+ - TODO
35
+ files:
36
+ - LICENSE
37
+ - README.rdoc
38
+ - Rakefile
39
+ - TODO
40
+ - init.rb
41
+ - lib/morpher_inflect/version.rb
42
+ - lib/morpher_inflect.rb
43
+ - spec/morpher_inflect_spec.rb
44
+ - spec/spec.opts
45
+ - spec/spec_helper.rb
46
+ has_rdoc: true
47
+ homepage: http://github.com/codesnik/morpher_inflect/
48
+ licenses: []
49
+
50
+ post_install_message:
51
+ rdoc_options: []
52
+
53
+ require_paths:
54
+ - lib
55
+ required_ruby_version: !ruby/object:Gem::Requirement
56
+ requirements:
57
+ - - ">="
58
+ - !ruby/object:Gem::Version
59
+ version: "0"
60
+ version:
61
+ required_rubygems_version: !ruby/object:Gem::Requirement
62
+ requirements:
63
+ - - ">="
64
+ - !ruby/object:Gem::Version
65
+ version: "0"
66
+ version:
67
+ requirements: []
68
+
69
+ rubyforge_project:
70
+ rubygems_version: 1.3.5
71
+ signing_key:
72
+ specification_version: 3
73
+ summary: Morpher.ru webservice client (Russian language inflection)
74
+ test_files: []
75
+