morpher_inflecter 0.0.1 → 0.0.3

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.
checksums.yaml CHANGED
@@ -1,15 +1,7 @@
1
1
  ---
2
- !binary "U0hBMQ==":
3
- metadata.gz: !binary |-
4
- MDYyNGM0NzQyMTJjMWFkY2FkNGI5MWVhZDNlNWI2NjAyM2I0YWViMw==
5
- data.tar.gz: !binary |-
6
- NDliNTkyNzkyNjg1MjZmNzUxYWQzNWY4YmU2ZmEyMjVhNWU3NjA3YQ==
2
+ SHA1:
3
+ metadata.gz: e7ff8832273fcc0b4df4c7d670b280144e172b01
4
+ data.tar.gz: 2b54567b82057bcc93748b5294f79950629bc4f6
7
5
  SHA512:
8
- metadata.gz: !binary |-
9
- ZmViMTczNTc0ZTAyZGRiZTViMDQ4MjhlOGRmN2I2MmI3YjcxMTZmMDhjYmNl
10
- MTJjM2I4NjQyZWI5MGY0ZmJiMzY0YWMzMzkxMjkyN2RjZWRkYjhkYzk3NjYy
11
- NmI3OTI2Mjg2MWJiYjU4NWVlMDIwYTMwMzFiYzRmNDczMDA1OGY=
12
- data.tar.gz: !binary |-
13
- NmQzYWE1ZTI3NzljNmYyOWRjY2RhYTc0YmVhYTY3MDAyNjNhZGUzZWFjNzg1
14
- ZGMzMzBhMTMwNDdlYWQ1YTk3NzczOTUxNDY4OWU1NzMyMjI4ZjM1MjZhNGVh
15
- M2EyNWQwMzNjODM4YzU3NTYxYTg1YmUzNjgwZGI1ODI4OGNiYzA=
6
+ metadata.gz: 251630f8c3b435f0911012533f0179e1560a5a361619d09812c7bb3515fb8dc66b0b8cd3e2513a62ad3c6bc46fa67bd2c1b11a5cb9c246d76f365bb85f44f934
7
+ data.tar.gz: f18e10cefbccdde0ebf9ccf219af3c42d6648d38b56dfaa463455d0a801141f280f721a2f40f9823900c25aab78ff90032da148c074055a422b65890edb90f28
@@ -1,3 +1,3 @@
1
1
  module MorpherInflecter
2
- VERSION = "0.0.1"
2
+ VERSION = "0.0.3"
3
3
  end
@@ -3,23 +3,44 @@
3
3
  require "morpher_inflecter/version"
4
4
  require 'rubygems'
5
5
  require 'open-uri'
6
- require 'nokogiri'
6
+ require 'json'
7
7
 
8
8
  module MorpherInflecter
9
+ URL = 'https://ws3.morpher.ru/russian/declension'.freeze
10
+
9
11
  # Падежи
10
12
  CASES = %w(И Р Д В Т П)
11
13
 
14
+ ERROR_CODES = {
15
+ "402" => ["1", "Превышен лимит на количество запросов в сутки. Перейдите на следующий тарифный план."],
16
+ "403" => ["3", "IP заблокирован."],
17
+ "495" => ["4", "Склонение числительных в declension не поддерживается. Используйте метод spell."],
18
+ "496" => ["5", "Не найдено русских слов."],
19
+ "400" => ["6", "Не указан обязательный параметр s."],
20
+ "402" => ["7", "Необходимо оплатить услугу."],
21
+ "498" => ["9", "Данный token не найден."],
22
+ "497" => ["10", "Неверный формат токена."],
23
+ "500" => ["11", "Ошибка сервера."],
24
+ "494" => ["12", "Указаны неправильные флаги."]
25
+ }
26
+
12
27
  # Класс для получения данных с веб-сервиса Морфера.
13
28
  class Inflection
14
- def get(text, login = nil, password = nil)
15
- url = 'http://morpher.ru/WebService.asmx/GetXml?'
16
- options = { :s => text }
17
- if login and password
18
- options[:username] = login
19
- options[:password] = password
29
+ def get(text, token = nil)
30
+ params = { s: text }
31
+ params[:token] = token if token
32
+
33
+ uri = URI(MorpherInflecter::URL)
34
+ uri.query = URI.encode_www_form(params)
35
+
36
+ JSON.parse( open(uri, 'Accept' => 'application/json').read )
37
+
38
+ rescue OpenURI::HTTPError => ex
39
+ error = { error: ex.message.strip }
40
+ if code = MorpherInflecter::ERROR_CODES[ex.message.strip]
41
+ error.merge!(code: code[0], message: code[1])
20
42
  end
21
- url = url + URI.encode(options.map{|key, val| "#{key}=#{val}"}.join('&'))
22
- Nokogiri.XML(open(url)) rescue nil
43
+ error
23
44
  end
24
45
  end
25
46
 
@@ -28,34 +49,33 @@ module MorpherInflecter
28
49
 
29
50
  # Возвращает хэш склонений в следуюшем формате
30
51
  # {:singular => [], :plural => []}
31
- # Если слово не найдено в словаре или произошла ошибка, будет возвращен код ошибки {:error => XXX}
32
- def self.inflections(word)
33
- inflections = {}
52
+ # Если слово не найдено в словаре или произошла ошибка, будет возвращен код ошибки { error: "XXX", code: "Y", message: 'error message' }
53
+ def self.inflections(word, options = {})
34
54
 
35
55
  lookup = cache_lookup(word)
36
56
  return lookup if lookup
57
+ resp = Inflection.new.get(word, options[:token])
58
+ inflections = {}
37
59
 
38
- doc = Inflection.new.get(word)
39
-
40
- return nil if doc.nil?
41
-
42
- unless doc.xpath('error/code').empty?
43
- inflections[:error] = doc.xpath('error/code').text.to_i
60
+ if resp[:error]
61
+ inflections = resp
44
62
  else
45
- singular = true unless doc.search('множественное').empty?
63
+ plural_only = resp['множественное'].nil?
64
+
65
+ inflections[:singular] = [] unless plural_only
66
+ inflections[:plural] = []
46
67
 
47
68
  CASES.each do |_case|
48
- nodes = doc.search(_case)
49
- if singular == true
50
- s = _case == 'И' ? word : nodes.first.text.to_s
51
- p = nodes.last.text.to_s
69
+ i = _case == 'И' ? word : resp[_case]
70
+
71
+ if plural_only
72
+ inflections[:plural] << i
52
73
  else
53
- p = _case == 'И' ? word : nodes.last.text.to_s
74
+ inflections[:singular] << i
75
+ inflections[:plural] << resp['множественное'][_case]
54
76
  end
55
-
56
- (inflections[:singular]||=[]) << s if singular
57
- (inflections[:plural]||=[]) << p if p
58
77
  end
78
+
59
79
  cache_store(word, inflections)
60
80
  end
61
81
 
@@ -15,12 +15,12 @@ Gem::Specification.new do |gem|
15
15
  gem.files = `git ls-files`.split($/)
16
16
  gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
17
17
  gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
18
+ gem.license = 'MIT'
18
19
  gem.require_paths = ["lib"]
19
20
 
20
21
  gem.has_rdoc = true
21
22
  gem.extra_rdoc_files = ["README.rdoc", "LICENSE.txt"]
22
23
 
23
- gem.add_dependency "nokogiri"
24
24
  gem.add_development_dependency "rspec", '2.6'
25
25
  gem.add_development_dependency "rake"
26
26
  end
@@ -4,102 +4,102 @@ require File.dirname(__FILE__) + '/spec_helper.rb'
4
4
 
5
5
  describe MorpherInflecter do
6
6
  before(:all) do
7
- @singular_noun_answer = <<EOS
8
- <?xml version="1.0" encoding="utf-8"?>
9
- <xml xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://morpher.ru/">
10
- <Р>рубина</Р>
11
- <Д>рубину</Д>
12
- <В>рубин</В>
13
- <Т>рубином</Т>
14
- <П>рубине</П>
15
- <множественное>
16
- <И>рубины</И>
17
- <Р>рубинов</Р>
18
- <Д>рубинам</Д>
19
- <В>рубины</В>
20
- <Т>рубинами</Т>
21
- <П>рубинах</П>
22
- </множественное>
23
- </xml>
24
- EOS
25
- @singular_noun_inflection = {:singular=>["рубин", "рубина", "рубину", "рубин", "рубином", "рубине"], :plural=>["рубины", "рубинов", "рубинам", "рубины", "рубинами", "рубинах"]}
26
-
27
- @plural_noun_answer = <<EOS
28
- <?xml version="1.0" encoding="utf-8"?>
29
- <xml xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://morpher.ru/">
30
- <Р>рубинов</Р>
31
- <Д>рубинам</Д>
32
- <В>рубины</В>
33
- <Т>рубинами</Т>
34
- <П>рубинах</П>
35
- </xml>
36
- EOS
37
- @plural_noun_inflection = {:plural=>["рубины", "рубинов", "рубинам", "рубины", "рубинами", "рубинах"]}
38
-
39
- @error_answer =<<EOS
40
- <error>
41
- <code>5</code>
42
- <message>Не найдено русских слов.</message>
43
- </error>
44
- EOS
45
- @error_code = {:error => 5}
7
+
8
+ @singular_noun_answer = '{
9
+ "Р": "рубина",
10
+ "Д": "рубину",
11
+ "В": "рубин",
12
+ "Т": "рубином",
13
+ "П": "рубине",
14
+ "множественное": {
15
+ "И": "рубины",
16
+ "Р": "рубинов",
17
+ "Д": "рубинам",
18
+ "В": "рубины",
19
+ "Т": "рубинами",
20
+ "П": "рубинах"
21
+ }
22
+ }'
23
+
24
+ @singular_noun_inflection = {
25
+ singular: ["рубин", "рубина", "рубину", "рубин", "рубином", "рубине"],
26
+ plural: ["рубины", "рубинов", "рубинам", "рубины", "рубинами", "рубинах"]
27
+ }
28
+
29
+ @plural_noun_answer = '{
30
+ "Р": "рубинов",
31
+ "Д": "рубинам",
32
+ "В": "рубины",
33
+ "Т": "рубинами",
34
+ "П": "рубинах"
35
+ }
36
+ '
37
+ @plural_noun_inflection = { plural: ["рубины", "рубинов", "рубинам", "рубины", "рубинами", "рубинах"] }
38
+
39
+ @error = { error: "496", code: "5", message: "Не найдено русских слов." }
40
+
41
+
46
42
  end
47
43
 
48
44
  before(:each) do
49
- @inflection = mock(:inflection)
45
+ @inflection = MorpherInflecter::Inflection.new
50
46
  MorpherInflecter::clear_cache
51
47
  end
52
48
 
53
49
  it "should return an hash of inflections for singular noun" do
54
- @inflection.stub!(:get).and_return(parsed_xml(@singular_noun_answer))
50
+ @inflection.stub_chain(:open, :read).and_return(@singular_noun_answer)
55
51
  MorpherInflecter::Inflection.should_receive(:new).and_return(@inflection)
56
52
  MorpherInflecter.inflections("рубин").should == @singular_noun_inflection
57
53
  end
58
54
 
59
55
  it "should return an hash of inflections for plural noun" do
60
- @inflection.stub!(:get).and_return(parsed_xml(@plural_noun_answer))
56
+ @inflection.stub_chain(:open, :read).and_return(@plural_noun_answer)
61
57
  MorpherInflecter::Inflection.should_receive(:new).and_return(@inflection)
62
58
  MorpherInflecter.inflections("рубины").should == @plural_noun_inflection
63
59
  end
64
60
 
65
61
  it "should return error when webservice returns error" do
66
- @inflection.stub!(:get).and_return(parsed_xml(@error_answer))
62
+ exception_io = mock('io')
63
+ exception_io.stub_chain(:status,:[],:message)
64
+ @inflection.stub(:open).and_raise(OpenURI::HTTPError.new('496',exception_io))
67
65
  MorpherInflecter::Inflection.should_receive(:new).and_return(@inflection)
68
- MorpherInflecter.inflections("рубин1").should == {:error => 5}
66
+ MorpherInflecter.inflections("рубин1").should == @error
69
67
  end
70
68
 
71
69
  it "should return nil when webservice does not return xml or connection failed" do
72
- @inflection.stub!(:get).and_return(nil)
70
+ exception_io = mock('io')
71
+ exception_io.stub_chain(:status,:[],:message)
72
+ @inflection.stub(:open).and_raise(OpenURI::HTTPError.new('502',exception_io))
73
+
73
74
  MorpherInflecter::Inflection.should_receive(:new).and_return(@inflection)
74
- MorpherInflecter.inflections("рубин").should == nil
75
+ MorpherInflecter.inflections("рубин").should == {error: '502'}
75
76
  end
76
77
 
77
78
  context 'Cache' do
78
79
  it "should cache successful lookups" do
79
- @inflection.stub!(:get).and_return(parsed_xml(@singular_noun_answer))
80
+ @inflection.stub!(:get).and_return(parsed_json(@singular_noun_answer))
80
81
  MorpherInflecter::Inflection.should_receive(:new).once.and_return(@inflection)
81
82
 
82
83
  2.times { MorpherInflecter.inflections("рубин") }
83
84
  end
84
85
 
85
- it "should NOT cache unseccussful lookups" do
86
- sample = nil
87
- @inflection.stub!(:get).and_return(sample)
86
+ it "should NOT cache unsuccessful lookups" do
87
+ @inflection.stub!(:get).and_return({error: "496"})
88
88
  MorpherInflecter::Inflection.should_receive(:new).twice.and_return(@inflection)
89
89
 
90
90
  2.times { MorpherInflecter.inflections("рубин") }
91
91
  end
92
92
 
93
- it "should NOT cache unseccussful lookups" do
94
- sample = parsed_xml(@singular_noun_answer)
93
+ it "should NOT cache unsuccessful lookups" do
94
+ sample = parsed_json(@singular_noun_answer)
95
95
  @inflection.stub!(:get).and_return(sample)
96
- MorpherInflecter::Inflection.should_receive(:new).once.and_return(@inflection)
96
+ MorpherInflecter::Inflection.should_receive(:new).once.and_return(@inflection)
97
97
 
98
98
  2.times { MorpherInflecter.inflections("рубин") }
99
99
  end
100
100
 
101
101
  it "should allow to clear cache" do
102
- sample = parsed_xml(@singular_noun_answer)
102
+ sample = parsed_json(@singular_noun_answer)
103
103
  @inflection.stub!(:get).and_return(sample)
104
104
  MorpherInflecter::Inflection.should_receive(:new).twice.and_return(@inflection)
105
105
 
data/spec/spec_helper.rb CHANGED
@@ -3,6 +3,6 @@ require 'rspec'
3
3
  $:.unshift(File.dirname(__FILE__) + '/../lib')
4
4
  require 'morpher_inflecter'
5
5
 
6
- def parsed_xml(text)
7
- Nokogiri::XML.parse(text)
6
+ def parsed_json(text)
7
+ JSON.parse(text)
8
8
  end
metadata CHANGED
@@ -1,29 +1,15 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: morpher_inflecter
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.1
4
+ version: 0.0.3
5
5
  platform: ruby
6
6
  authors:
7
7
  - Dmitry Penkin
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2013-09-24 00:00:00.000000000 Z
11
+ date: 2018-01-21 00:00:00.000000000 Z
12
12
  dependencies:
13
- - !ruby/object:Gem::Dependency
14
- name: nokogiri
15
- requirement: !ruby/object:Gem::Requirement
16
- requirements:
17
- - - ! '>='
18
- - !ruby/object:Gem::Version
19
- version: '0'
20
- type: :runtime
21
- prerelease: false
22
- version_requirements: !ruby/object:Gem::Requirement
23
- requirements:
24
- - - ! '>='
25
- - !ruby/object:Gem::Version
26
- version: '0'
27
13
  - !ruby/object:Gem::Dependency
28
14
  name: rspec
29
15
  requirement: !ruby/object:Gem::Requirement
@@ -42,14 +28,14 @@ dependencies:
42
28
  name: rake
43
29
  requirement: !ruby/object:Gem::Requirement
44
30
  requirements:
45
- - - ! '>='
31
+ - - ">="
46
32
  - !ruby/object:Gem::Version
47
33
  version: '0'
48
34
  type: :development
49
35
  prerelease: false
50
36
  version_requirements: !ruby/object:Gem::Requirement
51
37
  requirements:
52
- - - ! '>='
38
+ - - ">="
53
39
  - !ruby/object:Gem::Version
54
40
  version: '0'
55
41
  description: Morpher.ru inflections for russian proper and common nouns. Code inspired
@@ -61,8 +47,8 @@ extra_rdoc_files:
61
47
  - README.rdoc
62
48
  - LICENSE.txt
63
49
  files:
64
- - .gitignore
65
- - .travis.yml
50
+ - ".gitignore"
51
+ - ".travis.yml"
66
52
  - Gemfile
67
53
  - LICENSE.txt
68
54
  - README.rdoc
@@ -75,7 +61,8 @@ files:
75
61
  - spec/spec.opts
76
62
  - spec/spec_helper.rb
77
63
  homepage: http://github.com/dmitryp/morpher_inflecter/
78
- licenses: []
64
+ licenses:
65
+ - MIT
79
66
  metadata: {}
80
67
  post_install_message:
81
68
  rdoc_options: []
@@ -83,17 +70,17 @@ require_paths:
83
70
  - lib
84
71
  required_ruby_version: !ruby/object:Gem::Requirement
85
72
  requirements:
86
- - - ! '>='
73
+ - - ">="
87
74
  - !ruby/object:Gem::Version
88
75
  version: '0'
89
76
  required_rubygems_version: !ruby/object:Gem::Requirement
90
77
  requirements:
91
- - - ! '>='
78
+ - - ">="
92
79
  - !ruby/object:Gem::Version
93
80
  version: '0'
94
81
  requirements: []
95
82
  rubyforge_project: morpher_inflecter
96
- rubygems_version: 2.1.4
83
+ rubygems_version: 2.2.2
97
84
  signing_key:
98
85
  specification_version: 4
99
86
  summary: Morpher.ru webservice client (Russian language inflection)
@@ -101,3 +88,4 @@ test_files:
101
88
  - spec/morpher_inflecter_spec.rb
102
89
  - spec/spec.opts
103
90
  - spec/spec_helper.rb
91
+ has_rdoc: true