standalone_typograf 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
data/.DS_Store ADDED
Binary file
data/.gitignore ADDED
@@ -0,0 +1,19 @@
1
+ .DS_Store
2
+ *.gem
3
+ *.rbc
4
+ .bundle
5
+ .config
6
+ .yardoc
7
+ .idea/
8
+ Gemfile.lock
9
+ InstalledFiles
10
+ _yardoc
11
+ coverage
12
+ doc/
13
+ lib/bundler/man
14
+ pkg
15
+ rdoc
16
+ spec/reports
17
+ test/tmp
18
+ test/version_tmp
19
+ tmp
data/.rvmrc ADDED
@@ -0,0 +1 @@
1
+ rvm use 1.9.3@standalone_typograf --create
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in standalone_typograf.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2013 «Shilov Alexander»
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,86 @@
1
+ # StandaloneTypograf
2
+
3
+ **StandaloneTypograf** — gem для подготовки текста к публикации (замена кавычек на «ёлочки», тире и знаков ©).
4
+ Аналог «Типографа» студии Лебедева или сервисов подобных http://typograf.ru
5
+
6
+ "Струйка воды толщиной в одну спичку даёт утечку "200 литров в сутки!"", - сказал Афоня (c)
7
+
8
+ «Струйка воды толщиной в одну спичку даёт утечку „200 литров в сутки!“», — сказал Афоня ©
9
+
10
+
11
+ Ключевое отличие **StandaloneTypograf** от прочих типографских гемов:
12
+
13
+ - автономность (самостоятельная обработка текста не зависящая от сторонних сайтов и сервисов);
14
+ - выполняет прямую функцию (не преобразует в html, работает с plain текстом, UTF-8 символы (© вместо &#169)
15
+ - высокая скорость
16
+
17
+
18
+ ## Benchmark
19
+
20
+ Для теста была взята книга Андрея Кочергина «Как закалялась сталь 2» (954 строки, 32 000 слов, 757 знаков тире [-], 752 кавычки ["])
21
+
22
+ В тесте принимали участие следующие гемы:
23
+ - **typograf**, **multi_typograf** *(обертка сервиса typograf.ru)*;
24
+ - **als_typograf** *(обертка сервиса artlebedev.ru/tools/typograf/)*;
25
+ - **Gilenson** *(RuTils)*.
26
+
27
+ Результаты тестирования:
28
+ 1. **StandaloneTypograf, результат: 0,143 секунды**
29
+ 2. Gilenson, результат: 0.764 секунды (медленее в 5 раз)
30
+ 3. typograf, multi_typograf, выдали ошибку (макс. размер текста = 50 Kb)
31
+ 3. als_typograf, выдал ошибку (макс. размер текста = 32 Kb)
32
+
33
+ ## Installation
34
+
35
+ Ruby 1.9.3 - 2.0.0; Rails 3
36
+
37
+ Add this line to your application's Gemfile:
38
+
39
+ gem 'standalone_typograf'
40
+
41
+ And then execute:
42
+
43
+ $ bundle
44
+
45
+ Or install it yourself as:
46
+
47
+ $ gem install standalone_typograf
48
+
49
+
50
+ ## Использование
51
+
52
+ Пример использования:
53
+
54
+ require 'standalone_typograf'
55
+
56
+ text = StandaloneTypograf::Typograf.new('"StandaloneTypograf" - простой и быстрый, его можно использовать "на лету"')
57
+ text.dasherize # Преобразует все тире
58
+ text.signs # Заменит знаки (с) => ©
59
+ text.quotes # Преобразует кавычки
60
+
61
+ # Эти три метода можно заменить одной: prepare
62
+ text.prepare # => «StandaloneTypograf» — простой и быстрый, его можно использовать «на лету»
63
+
64
+ ## Параметры
65
+ ### Переопределение или добавление знаков
66
+
67
+ Чтобы переопределить знаки по-умолчанию или добавить собственные, передайте хеш *signs* или *signs_ru* (для русских заменяемых обозначений) 'знак' => 'заменяемый текст'.
68
+ Текст будет заменён только если он указан в круглых скобочках.
69
+
70
+ text = StandaloneTypograf::Typograf.new('(copy) 2013', signs: {'©' => 'copy'} )
71
+ text.signs # => "© 2013"
72
+
73
+ ### Переопределение кавычек
74
+
75
+ Чтопы переопределить кавычки (outer: внешние, inner: внутренние) передайте хеш quotes с ключем outer/inner и массивом из двух символов (левая и правая кавычки):
76
+
77
+ text = StandaloneTypograf::Typograf.new('"Мерседес"', quotes: { outer: ['«', '»'] } )
78
+ text.quotes # => "«Мерседес»'
79
+
80
+ ## Contributing
81
+
82
+ 1. Fork it
83
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
84
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
85
+ 4. Push to the branch (`git push origin my-new-feature`)
86
+ 5. Create new Pull Request
data/Rakefile ADDED
@@ -0,0 +1,9 @@
1
+ require 'rake/testtask'
2
+ Bundler::GemHelper.install_tasks
3
+
4
+ Rake::TestTask.new do |t|
5
+ t.libs << 'test'
6
+ end
7
+
8
+ desc 'Run tests'
9
+ task default: :test
@@ -0,0 +1,9 @@
1
+ #encoding: UTF-8
2
+
3
+ module StandaloneTypograf
4
+ module Dasherize
5
+ def dasherize
6
+ @text = @text.gsub(/- /i, '— ')
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,89 @@
1
+ #encoding: UTF-8
2
+
3
+ module StandaloneTypograf
4
+ module Quotes
5
+ QUOTES = {
6
+ outer: %w( « » ),
7
+ inner: %w( „ “ ),
8
+ }
9
+
10
+ SOURCE = {
11
+ double: '"'
12
+ }
13
+
14
+ def quotes
15
+ arr_text = @text.split('')
16
+ # [[0, :open], [10, :close]]
17
+ quotes_tree = build_quotes_tree(arr_text)
18
+ type_tree = build_type_tree(quotes_tree)
19
+ # [[5, :open, :inner], [10, :close, :inner]]
20
+
21
+ type_tree.each do |e|
22
+ # ОТКРЫВАЮЩИЕ
23
+ if e[1] == :open
24
+ arr_text[e[0]] = (e[2] == :inner) ? @quotes[:inner][0] : @quotes[:outer][0]
25
+ else
26
+ # ЗАКРЫВАЮЩИЕ
27
+ arr_text[e[0]] = (e[2] == :inner) ? @quotes[:inner][1] : @quotes[:outer][1]
28
+ end
29
+ end
30
+ @text = arr_text.join
31
+ end
32
+
33
+ # PRIVATE
34
+ #
35
+ private
36
+
37
+ # Вернет массив [[0, :open], [10, :close]]
38
+ # Где цифра - индекс кавычки в тексте,
39
+ # символ :open или :close - тип кавычки (открывающая или закрывающая)
40
+ #
41
+ def build_quotes_tree(arr_text)
42
+ quotes_tree = []
43
+ arr_text.each_with_index do |char, index|
44
+ _next_, _prev_ = index + 1, index - 1
45
+ # Если кавычка - первый символ в строке или за кавычкой примыкает буква,
46
+ # то эта кавычка - открывающая.
47
+ if char == SOURCE[:double]
48
+ if index == 0 || (arr_text[_next_] != ' ' and arr_text[_prev_] == ' ')
49
+ quotes_tree << [index, :open]
50
+ else
51
+ quotes_tree << [index, :close]
52
+ end
53
+ end
54
+ end
55
+ quotes_tree
56
+ end
57
+
58
+ # Вернет массив [[0, :open, :outer], [10, :close, :outer]]
59
+ #
60
+ def build_type_tree(quotes_tree)
61
+ type_tree = quotes_tree.clone
62
+ # [[0, :open], [10, :close]]
63
+ quotes_tree.each_with_index do |e, i|
64
+ even = (i%2 == 0)? true : false
65
+ # ОТКРЫВАЮЩИЕ КАВЫЧКИ
66
+ if e[1] == :open
67
+ # Каждая кавычка с четным индексом (или индексом == 0)
68
+ # внешняя.
69
+ if even || i == 0
70
+ type_tree[i] << :outer
71
+ else
72
+ type_tree[i] << :inner
73
+ end
74
+ end
75
+
76
+ # ЗАКРЫВАЮЩИЕ КАВЫЧКИ
77
+ if e[1] == :close
78
+ # Каждая нечётная кавычка (или кавычка с индексом = 1) - внешняя
79
+ if !even || i == 1
80
+ type_tree[i] << :outer
81
+ else
82
+ type_tree[i] << :inner
83
+ end
84
+ end
85
+ type_tree
86
+ end
87
+ end
88
+ end
89
+ end
@@ -0,0 +1,28 @@
1
+ #encoding: UTF-8
2
+
3
+ module StandaloneTypograf
4
+ module Signs
5
+
6
+ SIGNS = {
7
+ '©' => 'c',
8
+ '™' => 'tm',
9
+ '®' => 'r',
10
+ }
11
+ SIGNS_RU = {
12
+ '©' => 'с',
13
+ '™' => 'тм',
14
+ '®' => 'р',
15
+ }
16
+
17
+ def signs
18
+ result = @text.clone
19
+ @signs.each_pair do |sign, text|
20
+ result.gsub!(/[(]#{text}[)]/i, sign)
21
+ end
22
+ @signs_ru.each_pair do |sign, text|
23
+ result.gsub!(/[(]#{text}[)]/i, sign)
24
+ end
25
+ @text = result
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,5 @@
1
+ #encoding: UTF-8
2
+
3
+ module StandaloneTypograf
4
+ VERSION = '1.0.0'
5
+ end
@@ -0,0 +1,30 @@
1
+ #encoding: UTF-8
2
+
3
+ require 'standalone_typograf/version'
4
+ require 'standalone_typograf/dasherize'
5
+ require 'standalone_typograf/signs'
6
+ require 'standalone_typograf/quotes'
7
+
8
+ module StandaloneTypograf
9
+ class Typograf
10
+ include StandaloneTypograf::Dasherize
11
+ include StandaloneTypograf::Signs
12
+ include StandaloneTypograf::Quotes
13
+
14
+ def initialize(text, options={})
15
+ options[:signs] ||= SIGNS
16
+ options[:signs_ru] ||= SIGNS_RU
17
+ options[:quotes] ||= QUOTES
18
+ @signs, @signs_ru = SIGNS.merge(options[:signs]), SIGNS_RU.merge(options[:signs_ru])
19
+ @quotes = QUOTES.merge(options[:quotes])
20
+ @text = text
21
+ end
22
+
23
+ def prepare
24
+ self.dasherize
25
+ self.signs
26
+ self.quotes
27
+ @text
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,24 @@
1
+ #encoding: UTF-8
2
+
3
+ lib = File.expand_path('../lib', __FILE__)
4
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
5
+ require 'standalone_typograf/version'
6
+
7
+ Gem::Specification.new do |spec|
8
+ spec.name = 'standalone_typograf'
9
+ spec.version = StandaloneTypograf::VERSION
10
+ spec.authors = 'Alex Shilov'
11
+ spec.email = 'sashapashamasha@gmail.com'
12
+ spec.description = "Standalone (offline) client of the ArtLebedev's Studio Typograf service."
13
+ spec.summary = 'Very Fast&Simple Typograf fot the Russian text.'
14
+ spec.homepage = 'https://github.com/shlima/StandaloneTypograf'
15
+ spec.license = 'MIT'
16
+
17
+ spec.files = `git ls-files`.split($/)
18
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
19
+ spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
20
+ spec.require_paths = ['lib']
21
+
22
+ spec.add_development_dependency 'bundler', '~> 1.3'
23
+ spec.add_development_dependency 'rake'
24
+ end
data/test/test_dash.rb ADDED
@@ -0,0 +1,24 @@
1
+ #encoding: UTF-8
2
+
3
+ require 'test/unit'
4
+ require 'standalone_typograf'
5
+
6
+ class DashTest < Test::Unit::TestCase
7
+ def test_dasherize_left
8
+ text = StandaloneTypograf::Typograf.new('Привет,- это длинное тире!')
9
+ should = 'Привет,— это длинное тире!'
10
+ assert_equal text.dasherize, should
11
+ end
12
+
13
+ def test_dasherize_hyphen
14
+ text = StandaloneTypograf::Typograf.new('Яблоко - это фрукт. То-то и оно.')
15
+ should = 'Яблоко — это фрукт. То-то и оно.'
16
+ assert_equal text.dasherize, should
17
+ end
18
+
19
+ def test_no_dashes
20
+ text = StandaloneTypograf::Typograf.new('Яблоко есть фрукт.')
21
+ should = 'Яблоко есть фрукт.'
22
+ assert_equal text.dasherize, should
23
+ end
24
+ end
@@ -0,0 +1,37 @@
1
+ #encoding: UTF-8
2
+
3
+ require 'test/unit'
4
+ require 'standalone_typograf'
5
+
6
+ class PrepareTest < Test::Unit::TestCase
7
+ def test_prepare
8
+ source = <<-PLAIN
9
+ (р) 2013 кто-то, кого нельзя называть. "Артемий лебедев(тм), - "Взял мяч - хуяч"(с)"
10
+ PLAIN
11
+ text = StandaloneTypograf::Typograf.new(source)
12
+ should = <<-PLAIN
13
+ ® 2013 кто-то, кого нельзя называть. «Артемий лебедев™, — „Взял мяч — хуяч“©»
14
+ PLAIN
15
+ assert_equal text.prepare, should
16
+ end
17
+
18
+ def test_prepare_blank
19
+ source = <<-PLAIN
20
+ р 2013 кто-то, кого нельзя называть. Артемий лебедев тм, Если взял мяч, то хуяч с
21
+ PLAIN
22
+ text = StandaloneTypograf::Typograf.new(source)
23
+ should = source
24
+ assert_equal text.prepare, should
25
+ end
26
+
27
+ def test_prepare_redefinition
28
+ source = <<-PLAIN
29
+ (р) 2013 кто-то, кого нельзя называть. "Артемий лебедев(тм), - "Взял мяч - хуяч"(с)"
30
+ PLAIN
31
+ text = StandaloneTypograf::Typograf.new(source, quotes: {outer: ['&laquo;', '&raquo;']})
32
+ should = <<-PLAIN
33
+ ® 2013 кто-то, кого нельзя называть. &laquo;Артемий лебедев™, — „Взял мяч — хуяч“©&raquo;
34
+ PLAIN
35
+ assert_equal text.prepare, should
36
+ end
37
+ end
@@ -0,0 +1,22 @@
1
+ #encoding: UTF-8
2
+
3
+ require 'test/unit'
4
+ require 'standalone_typograf'
5
+
6
+ class QuotesTest < Test::Unit::TestCase
7
+ def test_quotes_o_i
8
+ text = StandaloneTypograf::Typograf.new('"Два "вида" "кавычек"" "Жесть"')
9
+ should = '«Два „вида“ „кавычек“» «Жесть»'
10
+ assert_equal text.quotes, should
11
+ end
12
+ def test_quotes_o
13
+ text = StandaloneTypograf::Typograf.new('"Один", "Два", "Три"')
14
+ should = '«Один», «Два», «Три»'
15
+ assert_equal text.quotes, should
16
+ end
17
+ def test_quotes_redefinition
18
+ text = StandaloneTypograf::Typograf.new('"Один", "Два", "Три"', quotes: {outer: ['**', '**;']})
19
+ should = '**Один**;, **Два**;, **Три**;'
20
+ assert_equal text.quotes, should
21
+ end
22
+ end
@@ -0,0 +1,30 @@
1
+ #encoding: UTF-8
2
+
3
+ require 'test/unit'
4
+ require 'standalone_typograf'
5
+
6
+ class SignsTest < Test::Unit::TestCase
7
+ def test_signs
8
+ text = StandaloneTypograf::Typograf.new('(р)(Р)(r)(R)(тм)(ТМ)(с)(С)(C)(c)')
9
+ should = '®®®®™™©©©©'
10
+ assert_equal text.signs, should
11
+ end
12
+
13
+ def test_no_signs
14
+ text = StandaloneTypograf::Typograf.new('Это чистый текст (yes)')
15
+ should = 'Это чистый текст (yes)'
16
+ assert_equal text.signs, should
17
+ end
18
+
19
+ def test_signs_option
20
+ text = StandaloneTypograf::Typograf.new('(copy) 2013', signs: {'©' => 'copy'} )
21
+ should = '© 2013'
22
+ assert_equal text.signs, should
23
+ end
24
+
25
+ def test_signs_ru_option
26
+ text = StandaloneTypograf::Typograf.new('(копи) 2013', signs_ru: {'&COPY;' => 'копи'} )
27
+ should = '&COPY; 2013'
28
+ assert_equal text.signs, should
29
+ end
30
+ end
metadata ADDED
@@ -0,0 +1,104 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: standalone_typograf
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Alex Shilov
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2013-03-30 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: bundler
16
+ requirement: !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ~>
20
+ - !ruby/object:Gem::Version
21
+ version: '1.3'
22
+ type: :development
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ none: false
26
+ requirements:
27
+ - - ~>
28
+ - !ruby/object:Gem::Version
29
+ version: '1.3'
30
+ - !ruby/object:Gem::Dependency
31
+ name: rake
32
+ requirement: !ruby/object:Gem::Requirement
33
+ none: false
34
+ requirements:
35
+ - - ! '>='
36
+ - !ruby/object:Gem::Version
37
+ version: '0'
38
+ type: :development
39
+ prerelease: false
40
+ version_requirements: !ruby/object:Gem::Requirement
41
+ none: false
42
+ requirements:
43
+ - - ! '>='
44
+ - !ruby/object:Gem::Version
45
+ version: '0'
46
+ description: Standalone (offline) client of the ArtLebedev's Studio Typograf service.
47
+ email: sashapashamasha@gmail.com
48
+ executables: []
49
+ extensions: []
50
+ extra_rdoc_files: []
51
+ files:
52
+ - .DS_Store
53
+ - .gitignore
54
+ - .rvmrc
55
+ - Gemfile
56
+ - LICENSE.txt
57
+ - README.md
58
+ - Rakefile
59
+ - lib/standalone_typograf.rb
60
+ - lib/standalone_typograf/dasherize.rb
61
+ - lib/standalone_typograf/quotes.rb
62
+ - lib/standalone_typograf/signs.rb
63
+ - lib/standalone_typograf/version.rb
64
+ - standalone_typograf.gemspec
65
+ - test/test_dash.rb
66
+ - test/test_prepare.rb
67
+ - test/test_quotes.rb
68
+ - test/test_signs.rb
69
+ homepage: https://github.com/shlima/StandaloneTypograf
70
+ licenses:
71
+ - MIT
72
+ post_install_message:
73
+ rdoc_options: []
74
+ require_paths:
75
+ - lib
76
+ required_ruby_version: !ruby/object:Gem::Requirement
77
+ none: false
78
+ requirements:
79
+ - - ! '>='
80
+ - !ruby/object:Gem::Version
81
+ version: '0'
82
+ segments:
83
+ - 0
84
+ hash: -4316510769190788404
85
+ required_rubygems_version: !ruby/object:Gem::Requirement
86
+ none: false
87
+ requirements:
88
+ - - ! '>='
89
+ - !ruby/object:Gem::Version
90
+ version: '0'
91
+ segments:
92
+ - 0
93
+ hash: -4316510769190788404
94
+ requirements: []
95
+ rubyforge_project:
96
+ rubygems_version: 1.8.25
97
+ signing_key:
98
+ specification_version: 3
99
+ summary: Very Fast&Simple Typograf fot the Russian text.
100
+ test_files:
101
+ - test/test_dash.rb
102
+ - test/test_prepare.rb
103
+ - test/test_quotes.rb
104
+ - test/test_signs.rb