standalone_typograf 1.0.2 → 2.0.0

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/.gitignore CHANGED
@@ -9,7 +9,6 @@ Gemfile.lock
9
9
  InstalledFiles
10
10
  _yardoc
11
11
  coverage
12
- doc/
13
12
  lib/bundler/man
14
13
  pkg
15
14
  rdoc
data/README.md CHANGED
@@ -1,52 +1,31 @@
1
- # StandaloneTypograf
1
+ ![StandaloneTypograf](https://raw.github.com/shlima/StandaloneTypograf/master/doc/logo.png)
2
2
 
3
- **StandaloneTypograf** — gem для подготовки текста к публикации (замена кавычек на «ёлочки», тире и знаков ©).
4
- Аналог «Типографа» студии Лебедева или сервисов подобных http://typograf.ru
3
+ **StandaloneTypograf** — gem для подготовки текста к публикации или типографирования текста на лету (вывод комментариев, например)
5
4
 
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
5
+ Пушкин писал Дельвигу: "Жду "Цыганов" и тотчас тисну...", (c) 1827 - А. С. Пушкин
36
6
 
37
- Add this line to your application's Gemfile:
38
-
39
- gem 'standalone_typograf'
40
-
41
- And then execute:
7
+ Превратится в:
8
+
9
+ Пушкин писал Дельвигу: «Жду „Цыганов“ и тотчас тисну…», © 1827 — А. С. Пушкин
10
+
11
+ ## Возможности
42
12
 
43
- $ bundle
13
+ - замена кавычек (поддерживаются внутренние и внешние кавычки);
14
+ - замена знаков (с), (тм), (р) на аналогичные ©, ™, ®. Буква в скобке может быть как английской, так и русской;
15
+ - замена знака ±
16
+ - короткое тире (между числами без отбивки);
17
+ - подстановка длинного тире (с использованием неразрывного пробела);
18
+ - привязка одно- и двухбуквенных слов к следующему за ними слову с помощью неразрывного пробела;
19
+ - привязка частиц (>=3) к предыдущему слову с помощью неразрывного пробела;
20
+ - замена всех 19 цельных символов дробей европейского вида, поддерживаемых стандартом Юникод.
44
21
 
45
- Or install it yourself as:
22
+ ## Отличия **StandaloneTypograf**
46
23
 
47
- $ gem install standalone_typograf
24
+ - автономность (самостоятельная обработка текста не зависящая от сторонних сайтов и сервисов);
25
+ - выполняет прямую функцию (не преобразует в html, работает с plain текстом, UTF-8 символы (© вместо &copy);
26
+ - корректная обработка двойных кавычек (в отличие от gilenson);
27
+ - высокая скорость;
48
28
 
49
-
50
29
  ## Использование
51
30
 
52
31
  Пример использования:
@@ -58,25 +37,59 @@ Or install it yourself as:
58
37
  text.signs # Заменит знаки (с) => ©
59
38
  text.quotes # Преобразует кавычки
60
39
 
61
- # Эти три метода можно заменить одной: prepare
62
- text.prepare # => «StandaloneTypograf» — простой и быстрый, его можно использовать «на лету»
63
-
40
+ # Эти три метода можно заменить одной командой: prepare
41
+ text.prepare # => «StandaloneTypograf» — простой и быстрый, его можно использовать «на лету»
42
+
64
43
  ## Параметры
44
+ ### Вызов определенных обработчиков
45
+
46
+ Вы можете вызвать только нужные вам типографы или использовать все одной командой *prepare*. Список поддерживаемых типографов:
47
+
48
+ - dasherize (тире)
49
+ - signs (символы)
50
+ - quotes (кавычки)
51
+ - dots (многоточие)
52
+ - endash (короткое тире)
53
+ - nbspace (неразрывные пробелы)
54
+ - fractions (дроби)
55
+
56
+ Или наоборот, вы можете исключить ненужный вам типограф, передав символьный массив в параметре *except* с ненужными обработчиками:
57
+
58
+ require 'standalone_typograf'
59
+ text = StandaloneTypograf::Typograf.new('(c) А. А. Шилов', except: [:fractions])
60
+ # Выполнит все преобразования кроме замены дробей
61
+ text.prepare
62
+
65
63
  ### Переопределение или добавление знаков
66
64
 
67
- Чтобы переопределить знаки по-умолчанию или добавить собственные, передайте хеш *signs* или *signs_ru* (для русских заменяемых обозначений) 'знак' => 'заменяемый текст'.
68
- Текст будет заменён только если он указан в круглых скобочках.
65
+ Чтобы переопределить знаки по-умолчанию или добавить собственные, передайте хеш *signs* или *signs_ru* (для русских заменяемых обозначений) 'заменяемый текст (в формате *regexp*)' => 'знак'.
69
66
 
70
- text = StandaloneTypograf::Typograf.new('(copy) 2013', signs: {'©' => 'copy'} )
67
+ text = StandaloneTypograf::Typograf.new('(copy) 2013', signs: {'[(]copy[)]' => '©'})
71
68
  text.signs # => "© 2013"
72
69
 
73
70
  ### Переопределение кавычек
74
71
 
75
- Чтопы переопределить кавычки (outer: внешние, inner: внутренние) передайте хеш quotes с ключем outer/inner и массивом из двух символов (левая и правая кавычки):
72
+ Чтобы переопределить кавычки (outer: внешние, inner: внутренние) передайте хеш quotes с ключем outer/inner и массивом из двух символов (левая и правая кавычки):
76
73
 
77
74
  text = StandaloneTypograf::Typograf.new('"Мерседес"', quotes: { outer: ['«', '»'] } )
78
75
  text.quotes # => "«Мерседес»'
79
76
 
77
+ ## Installation
78
+
79
+ Ruby 1.9.3 - 2.0.0; Rails 3-4
80
+
81
+ Add this line to your application's Gemfile:
82
+
83
+ gem 'standalone_typograf'
84
+
85
+ And then execute:
86
+
87
+ $ bundle
88
+
89
+ Or install it yourself as:
90
+
91
+ $ gem install standalone_typograf
92
+
80
93
  ## Contributing
81
94
 
82
95
  1. Fork it
@@ -84,3 +97,5 @@ Or install it yourself as:
84
97
  3. Commit your changes (`git commit -am 'Add some feature'`)
85
98
  4. Push to the branch (`git push origin my-new-feature`)
86
99
  5. Create new Pull Request
100
+
101
+
data/doc/fonts.md ADDED
@@ -0,0 +1,4 @@
1
+ Fonts:
2
+ Standalone = Voluptate_demo
3
+ Typograf = Telugu MN
4
+ 2 = PT Sans Caption
data/doc/logo.png ADDED
Binary file
data/doc/logo.psd ADDED
Binary file
@@ -1,10 +1,13 @@
1
- #encoding: UTF-8
1
+ # encoding: UTF-8
2
2
 
3
3
  require 'standalone_typograf/version'
4
4
  require 'standalone_typograf/dasherize'
5
5
  require 'standalone_typograf/signs'
6
6
  require 'standalone_typograf/quotes'
7
7
  require 'standalone_typograf/dots'
8
+ require 'standalone_typograf/endash'
9
+ require 'standalone_typograf/nbspace'
10
+ require 'standalone_typograf/fractions'
8
11
 
9
12
  module StandaloneTypograf
10
13
  class Typograf
@@ -12,22 +15,44 @@ module StandaloneTypograf
12
15
  include StandaloneTypograf::Signs
13
16
  include StandaloneTypograf::Quotes
14
17
  include StandaloneTypograf::Dots
18
+ include StandaloneTypograf::Endash
19
+ include StandaloneTypograf::Nbspace
20
+ include StandaloneTypograf::Fractions
15
21
 
16
22
  def initialize(text, options={})
17
23
  options[:signs] ||= SIGNS
18
24
  options[:signs_ru] ||= SIGNS_RU
19
25
  options[:quotes] ||= QUOTES
26
+ # except - массив с названием методов, которые необходимо исключить при выполнении
27
+ # *prepare*
28
+ @except = options[:except]
20
29
  @signs, @signs_ru = SIGNS.merge(options[:signs]), SIGNS_RU.merge(options[:signs_ru])
21
30
  @quotes = QUOTES.merge(options[:quotes])
22
31
  @text = text
23
32
  end
24
33
 
25
34
  def prepare
26
- self.dasherize
27
- self.signs
28
- self.quotes
29
- self.dots
35
+ call_method :dasherize
36
+ call_method :signs
37
+ call_method :quotes
38
+ call_method :dots
39
+ call_method :endash
40
+ call_method :nbspace
41
+ call_method :fractions
30
42
  @text
31
43
  end
44
+
45
+ # PRIVATE
46
+ #
47
+ private
48
+
49
+ # Выполняет метод только если он не был передан в параметре 'except'
50
+ # при создании объекта.
51
+ #
52
+ def call_method(name)
53
+ if @except.nil? || !@except.include?(name)
54
+ self.send(name)
55
+ end
56
+ end
32
57
  end
33
58
  end
@@ -1,9 +1,12 @@
1
- #encoding: UTF-8
1
+ # encoding: UTF-8
2
2
 
3
3
  module StandaloneTypograf
4
4
  module Dasherize
5
5
  def dasherize
6
+ # В ситуации, когда тире с отбивкой с обоих сторон,
7
+ # левый пробел - неразрывный.
8
+ @text = @text.gsub(/\s-\s/i, ' — ')
6
9
  @text = @text.gsub(/- /i, '— ')
7
10
  end
8
11
  end
9
- end
12
+ end
@@ -1,4 +1,4 @@
1
- #encoding: UTF-8
1
+ # encoding: UTF-8
2
2
 
3
3
  module StandaloneTypograf
4
4
  module Dots
@@ -0,0 +1,9 @@
1
+ # encoding: UTF-8
2
+
3
+ module StandaloneTypograf
4
+ module Endash
5
+ def endash
6
+ @text = @text.gsub(/(\d+)([-])(\d+)/i, '\1'+'–'+'\3')
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,35 @@
1
+ # encoding: UTF-8
2
+
3
+ module StandaloneTypograf
4
+ module Fractions
5
+ FRACTIONS = {
6
+ '1/4' => '¼',
7
+ '1/2' => '½',
8
+ '3/4' => '¾',
9
+ '1/7' => '⅐',
10
+ '1/9' => '⅑',
11
+ '1/10' => '⅒',
12
+ '1/3' => '⅓',
13
+ '2/3' => '⅔',
14
+ '1/5' => '⅕',
15
+ '2/5' => '⅖',
16
+ '3/5' => '⅗',
17
+ '4/5' => '⅘',
18
+ '1/6' => '⅙',
19
+ '5/6' => '⅚',
20
+ '1/8' => '⅛',
21
+ '3/8' => '⅜',
22
+ '5/8' => '⅝',
23
+ '7/8' => '⅞',
24
+ '0/3' => '↉'
25
+ }
26
+
27
+ def fractions
28
+ FRACTIONS.each_pair do |text, sign|
29
+ #@text = @text.gsub(/#{text}/i, sign)
30
+ @text = @text.gsub(/(\D)([#{text[0]}][\/][#{text[2]}])(\D)/i, '\1' + sign + '\3')
31
+ end
32
+ @text
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,42 @@
1
+ # encoding: UTF-8
2
+
3
+ module StandaloneTypograf
4
+ module Nbspace
5
+ PARTICLES = [
6
+ 'разве',
7
+ 'неужели',
8
+ 'едва',
9
+ 'вряд',
10
+ 'вроде',
11
+ 'якобы',
12
+ 'мол',
13
+ 'дескать',
14
+ 'даже',
15
+ 'ведь',
16
+ 'таки',
17
+ 'лишь',
18
+ 'почти',
19
+ 'только',
20
+ 'исключительно',
21
+ 'вон',
22
+ 'вот',
23
+ 'именно',
24
+ 'точь-в-точь',
25
+ 'приблизительно',
26
+ 'прямо',
27
+ ]
28
+ # Неразрывный пробел
29
+ def nbspace
30
+ # Одна буква - неразрывный пробел справа
31
+ @text = @text.gsub(/(\s)([a-zа-яА-Я])(\s)/i, '\1'+'\2'+' ')
32
+
33
+ # Двухбуквенные слова - наразрывные пробел справа
34
+ @text = @text.gsub(/(\s)([a-zа-яА-Я][a-zа-яА-Я])(\s)/i, '\1'+'\2'+' ')
35
+
36
+ # У частиц неразрывный пробел слева
37
+ PARTICLES.each { |p| @text = @text.gsub(/(\s)(#{p})/i, ' '+'\2') }
38
+
39
+ @text
40
+ end
41
+ end
42
+ end
@@ -1,4 +1,4 @@
1
- #encoding: UTF-8
1
+ # encoding: UTF-8
2
2
 
3
3
  module StandaloneTypograf
4
4
  module Quotes
@@ -1,28 +1,26 @@
1
- #encoding: UTF-8
1
+ # encoding: UTF-8
2
2
 
3
3
  module StandaloneTypograf
4
4
  module Signs
5
5
 
6
6
  SIGNS = {
7
- '©' => 'c',
8
- '' => 'tm',
9
- '®' => 'r',
7
+ '[(]c[)]' => '©',
8
+ '[(]tm[)]' => '',
9
+ '[(]r[)]' => '®',
10
+ '[+][-]' => '±',
10
11
  }
11
12
  SIGNS_RU = {
12
- '©' => 'с',
13
- '' => 'тм',
14
- '®' => 'р',
13
+ '[(]с[)]' => '©',
14
+ '[(]тм[)]' => '',
15
+ '[(]р[)]' => '®',
15
16
  }
16
17
 
17
18
  def signs
18
- result = @text.clone
19
- @signs.each_pair do |sign, text|
20
- result.gsub!(/[(]#{text}[)]/i, sign)
19
+ source = @signs.merge(@signs_ru).merge(SIGNS).merge(SIGNS_RU)
20
+ source.each_pair do |text, sign|
21
+ @text = @text.gsub(/#{text}/i, sign)
21
22
  end
22
- @signs_ru.each_pair do |sign, text|
23
- result.gsub!(/[(]#{text}[)]/i, sign)
24
- end
25
- @text = result
23
+ @text
26
24
  end
27
25
  end
28
26
  end
@@ -1,5 +1,5 @@
1
- #encoding: UTF-8
1
+ # encoding: UTF-8
2
2
 
3
3
  module StandaloneTypograf
4
- VERSION = '1.0.2'
4
+ VERSION = '2.0.0'
5
5
  end
data/test/test_dash.rb CHANGED
@@ -12,7 +12,7 @@ class DashTest < Test::Unit::TestCase
12
12
 
13
13
  def test_dasherize_hyphen
14
14
  text = StandaloneTypograf::Typograf.new('Яблоко - это фрукт. То-то и оно.')
15
- should = 'Яблоко — это фрукт. То-то и оно.'
15
+ should = 'Яблоко — это фрукт. То-то и оно.'
16
16
  assert_equal text.dasherize, should
17
17
  end
18
18
 
@@ -0,0 +1,12 @@
1
+ #encoding: UTF-8
2
+
3
+ require 'test/unit'
4
+ require 'standalone_typograf'
5
+
6
+ class EndashTest < Test::Unit::TestCase
7
+ def test_endash
8
+ text = StandaloneTypograf::Typograf.new('- В 2006-2012 годах я учился в каком-то университете.')
9
+ should = '- В 2006–2012 годах я учился в каком-то университете.'
10
+ assert_equal text.endash, should
11
+ end
12
+ end
@@ -0,0 +1,13 @@
1
+ #encoding: UTF-8
2
+
3
+ require 'test/unit'
4
+ require 'standalone_typograf'
5
+
6
+ class FractionsTest < Test::Unit::TestCase
7
+ # Дроби
8
+ def test_fractions
9
+ text = StandaloneTypograf::Typograf.new('В 1/3 всей воды на планете содержится 2/10 углекислого газа. 102/303')
10
+ should = 'В ⅓ всей воды на планете содержится 2/10 углекислого газа. 102/303'
11
+ assert_equal text.fractions, should
12
+ end
13
+ end
@@ -0,0 +1,26 @@
1
+ #encoding: UTF-8
2
+
3
+ require 'test/unit'
4
+ require 'standalone_typograf'
5
+
6
+ class NbspaceTest < Test::Unit::TestCase
7
+ def test_prepare_1word
8
+ # Неразрывный пробел справа от 'я' и 'в'
9
+ text = StandaloneTypograf::Typograf.new('Давно я ходил в лес')
10
+ should = 'Давно я ходил в лес'
11
+ assert_equal text.nbspace, should
12
+ end
13
+ def test_prepare_2words
14
+ # Неразрывный пробел справа от 'за'
15
+ text = StandaloneTypograf::Typograf.new('Сходи за пивом')
16
+ should = 'Сходи за пивом'
17
+ assert_equal text.nbspace, should
18
+ end
19
+
20
+ def test_particles
21
+ # У частиц неразрывный пробел слева
22
+ text = StandaloneTypograf::Typograf.new('Саша якобы принес водку')
23
+ should = 'Саша якобы принес водку'
24
+ assert_equal text.nbspace, should
25
+ end
26
+ end
data/test/test_prepare.rb CHANGED
@@ -10,28 +10,25 @@ class PrepareTest < Test::Unit::TestCase
10
10
  PLAIN
11
11
  text = StandaloneTypograf::Typograf.new(source)
12
12
  should = <<-PLAIN
13
- ® 2013 кто-то, кого нельзя называть. «Артемий лебедев™, — „Взял мяч — хуяч“©»
13
+ ® 2013 кто-то, кого нельзя называть. «Артемий лебедев™, — „Взял мяч — хуяч“©»
14
14
  PLAIN
15
15
  assert_equal text.prepare, should
16
16
  end
17
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
18
  def test_prepare_redefinition
28
19
  source = <<-PLAIN
29
20
  (р) 2013 кто-то, кого нельзя называть. "Артемий лебедев(тм), - "Взял мяч - хуяч"(с)"
30
21
  PLAIN
31
22
  text = StandaloneTypograf::Typograf.new(source, quotes: {outer: ['&laquo;', '&raquo;']})
32
23
  should = <<-PLAIN
33
- ® 2013 кто-то, кого нельзя называть. &laquo;Артемий лебедев™, — „Взял мяч — хуяч“©&raquo;
24
+ ® 2013 кто-то, кого нельзя называть. &laquo;Артемий лебедев™, — „Взял мяч — хуяч“©&raquo;
34
25
  PLAIN
35
26
  assert_equal text.prepare, should
36
27
  end
28
+
29
+ def test_except
30
+ text = StandaloneTypograf::Typograf.new('1/2+1/3', except: [:fractions])
31
+ should = '1/2+1/3'
32
+ assert_equal text.prepare, should
33
+ end
37
34
  end
data/test/test_signs.rb CHANGED
@@ -17,14 +17,20 @@ class SignsTest < Test::Unit::TestCase
17
17
  end
18
18
 
19
19
  def test_signs_option
20
- text = StandaloneTypograf::Typograf.new('(copy) 2013', signs: {'©' => 'copy'} )
20
+ text = StandaloneTypograf::Typograf.new('(copy) 2013', signs: {'[(]copy[)]' => '©'})
21
21
  should = '© 2013'
22
22
  assert_equal text.signs, should
23
23
  end
24
24
 
25
25
  def test_signs_ru_option
26
- text = StandaloneTypograf::Typograf.new('(копи) 2013', signs_ru: {'&COPY;' => 'копи'} )
26
+ text = StandaloneTypograf::Typograf.new('(копи) 2013', signs_ru: {'[(]копи[)]' => '&COPY;'})
27
27
  should = '&COPY; 2013'
28
28
  assert_equal text.signs, should
29
29
  end
30
+
31
+ def test_plus_minus
32
+ text = StandaloneTypograf::Typograf.new('В шахматной нотации символ +- означает, что после соответствующего хода преимущество имеют белые. Малахов +1.')
33
+ should = 'В шахматной нотации символ ± означает, что после соответствующего хода преимущество имеют белые. Малахов +1.'
34
+ assert_equal text.signs, should
35
+ end
30
36
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: standalone_typograf
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.0.2
4
+ version: 2.0.0
5
5
  prerelease:
6
6
  platform: ruby
7
7
  authors:
@@ -56,15 +56,24 @@ files:
56
56
  - LICENSE.txt
57
57
  - README.md
58
58
  - Rakefile
59
+ - doc/fonts.md
60
+ - doc/logo.png
61
+ - doc/logo.psd
59
62
  - lib/standalone_typograf.rb
60
63
  - lib/standalone_typograf/dasherize.rb
61
64
  - lib/standalone_typograf/dots.rb
65
+ - lib/standalone_typograf/endash.rb
66
+ - lib/standalone_typograf/fractions.rb
67
+ - lib/standalone_typograf/nbspace.rb
62
68
  - lib/standalone_typograf/quotes.rb
63
69
  - lib/standalone_typograf/signs.rb
64
70
  - lib/standalone_typograf/version.rb
65
71
  - standalone_typograf.gemspec
66
72
  - test/test_dash.rb
67
73
  - test/test_dots.rb
74
+ - test/test_endash.rb
75
+ - test/test_fractions.rb
76
+ - test/test_nbspace.rb
68
77
  - test/test_prepare.rb
69
78
  - test/test_quotes.rb
70
79
  - test/test_signs.rb
@@ -83,7 +92,7 @@ required_ruby_version: !ruby/object:Gem::Requirement
83
92
  version: '0'
84
93
  segments:
85
94
  - 0
86
- hash: -3393206938688602568
95
+ hash: 1046078892496407148
87
96
  required_rubygems_version: !ruby/object:Gem::Requirement
88
97
  none: false
89
98
  requirements:
@@ -92,7 +101,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
92
101
  version: '0'
93
102
  segments:
94
103
  - 0
95
- hash: -3393206938688602568
104
+ hash: 1046078892496407148
96
105
  requirements: []
97
106
  rubyforge_project:
98
107
  rubygems_version: 1.8.25
@@ -102,6 +111,9 @@ summary: Very Fast&Simple Typograf fot the Russian text.
102
111
  test_files:
103
112
  - test/test_dash.rb
104
113
  - test/test_dots.rb
114
+ - test/test_endash.rb
115
+ - test/test_fractions.rb
116
+ - test/test_nbspace.rb
105
117
  - test/test_prepare.rb
106
118
  - test/test_quotes.rb
107
119
  - test/test_signs.rb