okei 0.0.2

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.
Files changed (105) hide show
  1. checksums.yaml +7 -0
  2. data/.rubocop.yml +61 -0
  3. data/CHANGELOG.rdoc +13 -0
  4. data/LICENSE.rdoc +21 -0
  5. data/README.rdoc +91 -0
  6. data/Rakefile +52 -0
  7. data/app/controllers/okei/api/v1/responder.rb +30 -0
  8. data/app/controllers/okei/api/v1/units_controller.rb +41 -0
  9. data/app/models/okei/line.rb +63 -0
  10. data/app/models/okei/unit.rb +17 -0
  11. data/app/models/okei/word.rb +26 -0
  12. data/app/models/okei/words.rb +40 -0
  13. data/app/use_cases/okei/find_unit.rb +65 -0
  14. data/app/use_cases/okei/get_unit.rb +50 -0
  15. data/app/use_cases/okei/get_units.rb +45 -0
  16. data/app/views/okei/api/v1/units/_unit.json.jbuilder +6 -0
  17. data/app/views/okei/api/v1/units/errors.json.jbuilder +5 -0
  18. data/app/views/okei/api/v1/units/index.json.jbuilder +5 -0
  19. data/app/views/okei/api/v1/units/show.json.jbuilder +3 -0
  20. data/config/locales/ru.yml +12 -0
  21. data/config/routes.rb +12 -0
  22. data/db/migrate/20141004212500_create_okei_units.rb +20 -0
  23. data/db/migrate/20141004212501_populate_okei_units.rb +14 -0
  24. data/db/migrate/20141004212502_create_okei_words.rb +11 -0
  25. data/db/migrate/20141004212503_populate_okei_words.rb +15 -0
  26. data/db/seeds/units.json +4534 -0
  27. data/db/seeds/words.json +2462 -0
  28. data/lib/okei.rb +7 -0
  29. data/lib/okei/engine.rb +12 -0
  30. data/lib/okei/version.rb +4 -0
  31. data/lib/tasks/okei_tasks.rake +56 -0
  32. data/spec/controllers/okei/api/v1/responder_spec.rb +69 -0
  33. data/spec/controllers/okei/api/v1/units_controller_spec.rb +88 -0
  34. data/spec/dummy/README.rdoc +28 -0
  35. data/spec/dummy/Rakefile +6 -0
  36. data/spec/dummy/app/assets/javascripts/application.js +13 -0
  37. data/spec/dummy/app/assets/stylesheets/application.css +15 -0
  38. data/spec/dummy/app/controllers/application_controller.rb +5 -0
  39. data/spec/dummy/app/helpers/application_helper.rb +2 -0
  40. data/spec/dummy/app/views/layouts/application.html.erb +13 -0
  41. data/spec/dummy/bin/bundle +3 -0
  42. data/spec/dummy/bin/rails +4 -0
  43. data/spec/dummy/bin/rake +4 -0
  44. data/spec/dummy/config.ru +4 -0
  45. data/spec/dummy/config/application.rb +29 -0
  46. data/spec/dummy/config/boot.rb +5 -0
  47. data/spec/dummy/config/database.yml +25 -0
  48. data/spec/dummy/config/environment.rb +5 -0
  49. data/spec/dummy/config/environments/development.rb +37 -0
  50. data/spec/dummy/config/environments/production.rb +78 -0
  51. data/spec/dummy/config/environments/test.rb +39 -0
  52. data/spec/dummy/config/initializers/assets.rb +8 -0
  53. data/spec/dummy/config/initializers/backtrace_silencers.rb +7 -0
  54. data/spec/dummy/config/initializers/cookies_serializer.rb +3 -0
  55. data/spec/dummy/config/initializers/filter_parameter_logging.rb +4 -0
  56. data/spec/dummy/config/initializers/inflections.rb +16 -0
  57. data/spec/dummy/config/initializers/mime_types.rb +4 -0
  58. data/spec/dummy/config/initializers/session_store.rb +3 -0
  59. data/spec/dummy/config/initializers/wrap_parameters.rb +14 -0
  60. data/spec/dummy/config/locales/en.yml +23 -0
  61. data/spec/dummy/config/routes.rb +4 -0
  62. data/spec/dummy/config/secrets.yml +22 -0
  63. data/spec/dummy/db/schema.rb +39 -0
  64. data/spec/dummy/db/test.sqlite3 +0 -0
  65. data/spec/dummy/log/test.log +49831 -0
  66. data/spec/dummy/public/404.html +67 -0
  67. data/spec/dummy/public/422.html +67 -0
  68. data/spec/dummy/public/500.html +66 -0
  69. data/spec/dummy/public/favicon.ico +0 -0
  70. data/spec/examples/json_schemas/error.json +14 -0
  71. data/spec/examples/json_schemas/get_errors.json +18 -0
  72. data/spec/examples/json_schemas/get_unit.json +13 -0
  73. data/spec/examples/json_schemas/get_units.json +17 -0
  74. data/spec/examples/json_schemas/unit.json +20 -0
  75. data/spec/factories/units.rb +18 -0
  76. data/spec/factories/words.rb +7 -0
  77. data/spec/models/okei/line_spec.rb +61 -0
  78. data/spec/models/okei/unit_spec.rb +170 -0
  79. data/spec/models/okei/word_spec.rb +75 -0
  80. data/spec/models/okei/words_spec.rb +64 -0
  81. data/spec/requests/okei/api/v1/find_unit_spec.rb +65 -0
  82. data/spec/requests/okei/api/v1/get_unit_spec.rb +57 -0
  83. data/spec/requests/okei/api/v1/get_units_spec.rb +64 -0
  84. data/spec/routing/okei/api/v1/units_routing_spec.rb +56 -0
  85. data/spec/spec_helper.rb +9 -0
  86. data/spec/support/initializers/caching.rb +20 -0
  87. data/spec/support/initializers/coveralls.rb +4 -0
  88. data/spec/support/initializers/database_cleaner.rb +24 -0
  89. data/spec/support/initializers/factory_girl.rb +6 -0
  90. data/spec/support/initializers/factory_girl_rails.rb +1 -0
  91. data/spec/support/initializers/focus.rb +5 -0
  92. data/spec/support/initializers/garbage_collection.rb +11 -0
  93. data/spec/support/initializers/i18n.rb +1 -0
  94. data/spec/support/initializers/migrations.rb +3 -0
  95. data/spec/support/initializers/rails.rb +6 -0
  96. data/spec/support/initializers/random_order.rb +4 -0
  97. data/spec/support/initializers/rspec.rb +10 -0
  98. data/spec/support/initializers/timecop.rb +1 -0
  99. data/spec/support/matchers/controllers.rb +14 -0
  100. data/spec/support/matchers/json_schema.rb +10 -0
  101. data/spec/use_cases/okei/find_unit_spec.rb +77 -0
  102. data/spec/use_cases/okei/get_unit_spec.rb +64 -0
  103. data/spec/use_cases/okei/get_units_spec.rb +65 -0
  104. data/spec/views/okei/api/v1/units/_unit.json_spec.rb +24 -0
  105. metadata +400 -0
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: ff65991eed851bbc0d94adecc0f7f69c42926775
4
+ data.tar.gz: 618886df241a9e412715b0c74a5a95fb90b400b3
5
+ SHA512:
6
+ metadata.gz: 1fe760dccd23afc881a70df294650ec9853b7067574e1dbe3257b6944fcb825f159e8479183084f6e3565b59309024ba876b78740d84ef771d556f8adf1ebc77
7
+ data.tar.gz: c5a7197958e49539f73f941564a4e46b9fc80822d0f4b61c511cb308dbf2e94ec1876e4e0e4640ae7b4e4af982dfd97840b4a66c3d2c073a9464945b054a89df
@@ -0,0 +1,61 @@
1
+ AllCops:
2
+ Exclude:
3
+ - 'spec/dummy/**/*'
4
+ - 'Rakefile'
5
+
6
+ Lint/HandleExceptions:
7
+ Exclude:
8
+ - 'spec/**/*'
9
+
10
+ Lint/RescueException:
11
+ Exclude:
12
+ - 'spec/**/*'
13
+
14
+ Style/AccessorMethodName:
15
+ Exclude:
16
+ - 'spec/**/*'
17
+
18
+ Style/AsciiComments:
19
+ Enabled: false
20
+
21
+ Style/ClassAndModuleChildren:
22
+ Exclude:
23
+ - 'spec/**/*'
24
+
25
+ Style/Documentation:
26
+ Exclude:
27
+ - 'spec/**/*'
28
+ - 'db/**/*'
29
+
30
+ Style/EmptyLinesAroundBody:
31
+ Enabled: false
32
+
33
+ Style/EmptyLineBetweenDefs:
34
+ Exclude:
35
+ - 'spec/**/*'
36
+
37
+ Style/MethodLength:
38
+ Exclude:
39
+ - 'db/**/*'
40
+
41
+ Style/RaiseArgs:
42
+ EnforcedStyle: compact
43
+
44
+ Style/SingleLineMethods:
45
+ Exclude:
46
+ - 'spec/**/*'
47
+
48
+ Style/SpecialGlobalVars:
49
+ Exclude:
50
+ - 'Gemfile'
51
+ - '*.gemspec'
52
+
53
+ Style/StringLiterals:
54
+ EnforcedStyle: double_quotes
55
+
56
+ Style/SingleSpaceBeforeFirstArg:
57
+ Enabled: false
58
+
59
+ Style/TrivialAccessors:
60
+ Exclude:
61
+ - 'spec/**/*'
@@ -0,0 +1,13 @@
1
+ = CHANGELOG
2
+
3
+ == 2014-10-04 0.0.1-alpha
4
+
5
+ === Added
6
+
7
+ === Deleted
8
+
9
+ === Fixed
10
+
11
+ === Deprecated
12
+
13
+ === Security
@@ -0,0 +1,21 @@
1
+ = The MIT License
2
+
3
+ Copyright (c) 2014 Andrew Kozin, https://github.com/nepalez
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,91 @@
1
+ = Единицы измерения
2
+
3
+ {<img src="http://img.shields.io/travis/nepalez/okei.svg?style=flat" alt="Bild Status" />}[https://travis-ci.org/nepalez/okei]
4
+ {<img src="http://img.shields.io/codeclimate/github/nepalez/okei.svg?style=flat" alt="Code Metrics" />}[https://codeclimate.com/github/nepalez/okei]
5
+ {<img src="http://img.shields.io/gemnasium/nepalez/okei.svg?style=flat" alt="Dependency Status" />}[https://gemnasium.com/nepalez/okei]
6
+ {<img src="http://img.shields.io/coveralls/nepalez/okei.svg?style=flat" alt="Coverage Status" />}[https://coveralls.io/r/nepalez/okei]
7
+ {<img src="http://img.shields.io/badge/license-MIT-blue.svg?style=flat" alt="License" />}[https://github.com/nepalez/okei/blob/master/LICENSE.rdoc]
8
+
9
+ == О проекте
10
+
11
+ Модуль описывает единицы измерения по стандартам, действующим в Российской Федерации.
12
+ Является плагином Rails 4.1 и выше.
13
+
14
+ В список включены единицы измерения в соответствии со следующими стандартами:
15
+
16
+ * {ОКЕИ}[https://ru.wikipedia.org/wiki/%D0%9E%D0%B1%D1%89%D0%B5%D1%80%D0%BE%D1%81%D1%81%D0%B8%D0%B9%D1%81%D0%BA%D0%B8%D0%B9_%D0%BA%D0%BB%D0%B0%D1%81%D1%81%D0%B8%D1%84%D0%B8%D0%BA%D0%B0%D1%82%D0%BE%D1%80_%D0%B5%D0%B4%D0%B8%D0%BD%D0%B8%D1%86_%D0%B8%D0%B7%D0%BC%D0%B5%D1%80%D0%B5%D0%BD%D0%B8%D1%8F] (Общероссийский классификатор единиц измерения);
17
+ * {ГОСT 8.417-2002}[https://ru.wikipedia.org/wiki/%D0%93%D0%9E%D0%A1%D0%A2_8.417] (Государственная система обеспечения единства измерений. Единицы величин);
18
+ * {Рекомендация № 20 РГ 4 ЕЭК ООН}[http://www.unece.org/tradewelcome/areas-of-work/un-centre-for-trade-facilitation-and-e-business-uncefact/outputs/cefactrecommendationsrec-index/list-of-trade-facilitation-recommendations-n-16-to-20.html] "Коды единиц измерения, используемых в международной торговле" (Версия 9).
19
+
20
+ Модуль объявляет:
21
+
22
+ * Модель единиц измерения (<tt>Okei::Unit</tt>);
23
+ * Набор сервисов (use cases) для работы с единицами измерения;
24
+ * RESTful public API для доступа к списку единиц измерения и отдельным записям.
25
+
26
+ === Модель единиц измерения
27
+
28
+ <tt>Okei::Unit</tt>:: Описывает единицу измерения согласно действующим стандартам. Единица идентифицируется уникальным кодом по {стандарту UUID}[https://ru.wikipedia.org/wiki/UUID].
29
+
30
+ === Сервисы (use cases)
31
+
32
+ <tt>Okei::GetUnit</tt>:: Возвращает единицу измерения по указанному <tt>uuid</tt>
33
+ <tt>Okei::GetUnits</tt>:: Возвращает список всех единиц с возможностью отбора по виду измерений.
34
+ <tt>Okei::FindUnit</tt>:: Возвращает единицу измерения по названию.
35
+
36
+ === RESTful public API
37
+
38
+ API содержит следующие маршруты для доступа к единицам измерения:
39
+
40
+ <tt>GET /api/v1/units</tt>:: Перечень единиц с возможностью отбора по виду измерений.
41
+ <tt>GET /api/v1/units/{uuid}</tt>:: Поиск единицы измерения по <tt>uuid</tt>.
42
+ <tt>GET /api/v1/units/seach</tt>:: Поиск единицы измерения по названию.
43
+
44
+ Подробное описание см. в { API Blueprint }[http://docs.unitsapi.apiary.io].
45
+
46
+ При установке модуля рекомендуется использовать соответствующее поле имен
47
+ (например, <tt>/okei</tt>).
48
+
49
+ == Установка модуля
50
+
51
+ Добавьте строку в Gemfile:
52
+
53
+ gem "okei"
54
+
55
+ и затем вызовите из командной строки:
56
+
57
+ $ bundle
58
+
59
+ или установите модуль вручную:
60
+
61
+ $ gem install okei
62
+
63
+ После установки выполните в командной строке:
64
+
65
+ $ rake okei:install
66
+
67
+ При этом в файл <tt>/config/routes.rb</tt> проекта будет добавлена строка,
68
+ добавляющая адреса RESTful public API модуля. По умолчанию адреса добавляются
69
+ в поле имен <tt>/okei</tt>, т.ч. API становится доступен по адресам:
70
+
71
+ * <tt>GET {адрес вашего проекта}/okei/api/v1/units</tt>
72
+ * <tt>GET {адрес вашего проекта}/okei/api/v1/units/{uuid}</tt>
73
+ * <tt>GET {адрес вашего проекта}/okei/api/v1/units/search</tt>
74
+
75
+ == Contributing (en)
76
+
77
+ 1. Fork it ( https://github.com/nepalez/okei/fork )
78
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
79
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
80
+ 4. Push to the branch (`git push origin my-new-feature`)
81
+ 5. Create a new Pull Request
82
+
83
+ == Лицензия
84
+
85
+ Модуль распространяется на условиях свободной {лицензии MIT}[LICENSE.rdoc].
86
+
87
+ == Язык документации
88
+
89
+ Помимо данного описания и { API Blueprint }[http://docs.unitsapi.apiary.io],
90
+ выполненных на русском языке, остальная документация доступна только
91
+ по-английски.
@@ -0,0 +1,52 @@
1
+ begin
2
+ require "bundler/setup"
3
+ rescue LoadError
4
+ puts "You must `gem install bundler` and `bundle install` to run rake tasks"
5
+ end
6
+
7
+ begin
8
+ require "rdoc/task"
9
+ rescue LoadError
10
+ require "rdoc/rdoc"
11
+ require "rake/rdoctask"
12
+ RDoc::Task = Rake::RDocTask
13
+ end
14
+
15
+ RDoc::Task.new(:rdoc) do |rdoc|
16
+ rdoc.rdoc_dir = "rdoc"
17
+ rdoc.title = "Okei"
18
+ rdoc.options << "--line-numbers"
19
+ rdoc.rdoc_files.include "README.rdoc"
20
+ rdoc.rdoc_files.include "lib/**/*.rb"
21
+ end
22
+
23
+ Bundler::GemHelper.install_tasks
24
+
25
+ APP_RAKEFILE = File.expand_path "../spec/dummy/Rakefile", __FILE__
26
+ load "rails/tasks/engine.rake"
27
+
28
+ require "bundler/gem_tasks"
29
+ require "rspec/core/rake_task"
30
+
31
+ RSpec::Core::RakeTask.new :spec
32
+
33
+ task :migrate do
34
+ sh "bundle exec rake db:migrate RAILS_ENV=test"
35
+ end
36
+
37
+ task default: [:migrate] do
38
+ sh "mkdir spec/dummy/tmp" do |*|
39
+ nunitSuccessFlag = false
40
+ end
41
+ sh "mkdir spec/dummy/tmp/cache" do |*|
42
+ nunitSuccessFlag = false
43
+ end
44
+ sh "bundle exec rspec spec"
45
+ end
46
+
47
+ task :full do
48
+ sh "coveralls report"
49
+ sh "rubocop"
50
+ sh "metric_fu"
51
+ sh "inch"
52
+ end
@@ -0,0 +1,30 @@
1
+ # encoding: utf-8
2
+
3
+ module Okei
4
+ module Api
5
+ module V1
6
+
7
+ # Responds to client depending on use case results
8
+ class Responder < ::ApplicationController
9
+
10
+ # Renders list of units of measure.
11
+ def on_success(units)
12
+ @units = units
13
+ render "index"
14
+ end
15
+
16
+ # Renders a unit of measure.
17
+ def on_found(unit)
18
+ @unit = unit
19
+ render "show"
20
+ end
21
+
22
+ # Renders an error message.
23
+ def on_not_found(messages)
24
+ @messages = messages
25
+ render "errors", status: 404
26
+ end
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,41 @@
1
+ # encoding: utf-8
2
+
3
+ module Okei
4
+ module Api
5
+ module V1
6
+
7
+ # Controller for getting units
8
+ class UnitsController < Responder
9
+
10
+ # Returns either all units of measure or units of given measure.
11
+ def index
12
+ run_case GetUnits, with: :measure
13
+ end
14
+
15
+ # Finds a unit of measure by uuid.
16
+ def show
17
+ run_case GetUnit, with: :uuid
18
+ end
19
+
20
+ # Finds a unit of measure by text
21
+ def search
22
+ run_case FindUnit, with: :text
23
+ end
24
+
25
+ private
26
+
27
+ # Initializes a corresponding use case (service) with allowed params,
28
+ # subscribes for its results and then runs a use case.
29
+ #
30
+ # After running, the use case will call a method defined in the
31
+ # `Responder` parent class.
32
+ #
33
+ def run_case(klass, with:)
34
+ use_case = klass.new params.permit(*with)
35
+ use_case.subscribe self, prefix: :on
36
+ use_case.run
37
+ end
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,63 @@
1
+ # encoding: utf-8
2
+
3
+ module Okei
4
+
5
+ # Converts source string to standardized line of text with:
6
+ #
7
+ # * cyrillic letters un upper register
8
+ # * numbers
9
+ # * ^ - a symbol of word break
10
+ # * slashes
11
+ # * spaces
12
+ # * %
13
+ #
14
+ # Line.new "1000шт в условн.эквивал."
15
+ # # => "1000 ШТ В УСЛОВН ЭКВИВАЛ"
16
+ #
17
+ class Line < String
18
+
19
+ def initialize(str = "")
20
+ super str.to_s.mb_chars.upcase
21
+ to_cyrillic
22
+ remove_dots_and_commas
23
+ clear_text
24
+ add_breaks
25
+ end
26
+
27
+ private
28
+
29
+ # Converts latin letters to corresponding cyrillic
30
+ def to_cyrillic
31
+ {
32
+ "A" => "А", "B" => "В", "C" => "С", "D" => "Д", "E" => "Е",
33
+ "G" => "Д", "H" => "Н", "K" => "К", "M" => "М", "N" => "П",
34
+ "O" => "О", "P" => "Р", "Q" => "Д", "R" => "Г", "T" => "Т",
35
+ "U" => "И", "X" => "Х", "Y" => "У"
36
+ }.each { |lat, cyr| gsub! lat, cyr }
37
+ end
38
+
39
+ # Remove dots and commas except for dots between digits
40
+ def remove_dots_and_commas
41
+ gsub!(/\.+/, ",")
42
+ gsub!(/(\d),(\d)/, '\1.\2')
43
+ gsub!(/,/, " ")
44
+ end
45
+
46
+ # Removes unwanted symbols.
47
+ def clear_text
48
+ gsub!(/\%-[^\s]+/, "%")
49
+ gsub!(/[^А-Я\d\.\s\/\%]/, " ")
50
+ gsub!(/\A[^А-Я\d]+|[^А-Я\d]+\z/, " ")
51
+ gsub!(/\s{2,}/, " ")
52
+ strip!
53
+ end
54
+
55
+ # Add ^ to mark word breaks
56
+ def add_breaks
57
+ gsub!(
58
+ /\A(НАНО|МИКРО|МИЛЛИ|САНТИ|ПОЛ|ДЕКА|ДЕЦИ|ГЕКТО|КИЛО|МЕГА|ТЕРА)/, '\1 ^ '
59
+ )
60
+ gsub!(/([А-Я])[\s\.^]*(2|3)(?!\d)/, '\1 ^ \2')
61
+ end
62
+ end
63
+ end
@@ -0,0 +1,17 @@
1
+ # encoding: utf-8
2
+
3
+ module Okei
4
+
5
+ # Stores and validates units of measure
6
+ class Unit < ActiveRecord::Base
7
+
8
+ UUID_FORMAT = /\A[\d|a-f]{8}-([\d|a-f]{4}-){3}[\d|a-f]{12}\z/
9
+ NUM_FORMAT = /\A\d{3}\z/
10
+
11
+ validates :uuid, :code, :name, :base, :factor, :measure, presence: true
12
+ validates :uuid, :code, :name, uniqueness: true, allow_nil: true
13
+ validates :factor, allow_nil: true, numericality: { greater_than: 0.0 }
14
+ validates :num, allow_nil: true, format: { with: NUM_FORMAT }
15
+ validates :uuid, allow_nil: true, format: { with: UUID_FORMAT }
16
+ end
17
+ end
@@ -0,0 +1,26 @@
1
+ # encoding: utf-8
2
+
3
+ module Okei
4
+
5
+ # Stores dictionary of words:
6
+ #
7
+ # Word.new synonym: "МЕТРЫ", text: "М"
8
+ # Word.new synonym: "МЕТР", text: "М"
9
+ #
10
+ # ...and units in their standard representation:
11
+ #
12
+ # Word.new synonym: "КВ М", text: "М2"
13
+ # Word.new synonym: "М КВ", text: "М2"
14
+ #
15
+ class Word < ActiveRecord::Base
16
+
17
+ validates :synonym, :text, presence: true
18
+ validates :synonym, uniqueness: { case_sensitive: false }, allow_nil: true
19
+
20
+ # Translates the line if a translation exists.
21
+ # Otherwise returns source line unchanged.
22
+ def self.translate(line)
23
+ find_by_synonym(line).try(:text) || line
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,40 @@
1
+ # encoding: utf-8
2
+
3
+ module Okei
4
+
5
+ # Breaks the source string to words properly:
6
+ #
7
+ # Words.new "М3 96% ЧИСТОГО СПИРТА /ЧЕЛ"
8
+ # # => ["М", "^", "3", "96", "%", "ЧИСТОГО", "СПИРТА", "/", "ЧЕЛ"]
9
+ #
10
+ class Words < Array
11
+
12
+ def initialize(line = "")
13
+ @line = line.to_s
14
+ super @line.scan(/[А-Я]+|\d+.\d+|\d+|\/|\^|\%/)
15
+ end
16
+
17
+ # Maps words back to `Words` (not a base `Array`):
18
+ #
19
+ # ["9.8", "М", "/", "С", "^", "2"].map { |i| i }.class
20
+ # # => Words
21
+ #
22
+ # The method can be combined with `to_s`:
23
+ #
24
+ # ["9.8", "М", "/", "С", "^", "2"].map { |i| i.lower }.to_s
25
+ # # => "9.8 м/с2"
26
+ #
27
+ def map
28
+ Words.new super
29
+ end
30
+
31
+ # Joins words back to string when necessary:
32
+ #
33
+ # ["М", "^", "3", "96", "ПРОЦ", "ЧИСТОГО", "СПИРТА", "/", "ЧЕЛ"].to_s
34
+ # # => "М3 96 ПРОЦ ЧИСТОГО СПИРТА/ЧЕЛ"
35
+ #
36
+ def to_s
37
+ join(" ").gsub(" ^ ", "").gsub(" / ", "/")
38
+ end
39
+ end
40
+ end