typograf 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.
@@ -0,0 +1,17 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ .yardoc
6
+ Gemfile.lock
7
+ InstalledFiles
8
+ _yardoc
9
+ coverage
10
+ doc/
11
+ lib/bundler/man
12
+ pkg
13
+ rdoc
14
+ spec/reports
15
+ test/tmp
16
+ test/version_tmp
17
+ tmp
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in typograf.gemspec
4
+ gemspec
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2012 Stereobooster
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.
@@ -0,0 +1,77 @@
1
+ # Typograf
2
+
3
+ Universal tool for preparing russian text for web publishing. Ruby wrapper for typograf.ru webservice
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ gem 'typograf'
10
+
11
+ And then execute:
12
+
13
+ $ bundle
14
+
15
+ Or install it yourself as:
16
+
17
+ $ gem install typograf
18
+
19
+ ## Usage
20
+
21
+ ```ruby
22
+ require "typograf"
23
+
24
+ Typograf.process('text')
25
+ ```
26
+
27
+ You can pass second argument - hash of options.
28
+
29
+ ### Default options
30
+
31
+ ```ruby
32
+ {
33
+ :tags => 1, # 0 — не расставлять; 1 — расставлять
34
+ :tags_delete => 0, # 0 — не удалять; 1 — удалять до типографирования; 2 — удалять после типографирования
35
+ :paragraph => {
36
+ :insert => 1, # 1 — ставить; 0 — не ставить
37
+ # теги задают внешний вид обрамления параграфа, начальные и конечные теги соответственно (могут быть пустыми)
38
+ :start => '<p>',
39
+ :end => '</p>'
40
+ },
41
+ :newline => {
42
+ :tag => '<br/>', # теги перевода строки.
43
+ :insert => 1 # перевод строки: 1 — ставить; 0 — не ставить
44
+ },
45
+ :cms_new_line => 0, # Переводы строк <p>&nbsp;</p>
46
+ :dos_text => 0, # удаляет одинарные переводы строк и переносы: 0 — не удалять; 1 — удалять
47
+ :nowraped => {
48
+ :insert => 1, # 1 — ставить; 0 — не ставить
49
+ :nonbsp => 0, # 0 — не использовать неразрывные конструкции вместо (неразрывного пробела); 1 — наоборот
50
+ :length => 0, # не объединять в неразрывные конструкции слова, написанные через дефис, с общей длинной больше N знаков. Если 0 то не используется
51
+ :start => '<nobr>',
52
+ :end => '</nobr>'
53
+ },
54
+ :hanging_punct => 0, # висячая пунктуация: 1 — использовать; 0 — не использовать
55
+ :hanging_line => 0, # висячие строки: 1 — удалять; 0 — не удалять
56
+ :minus_sign => '&ndash;', # указывает какой символ использовать вместо знака минус: — &ndash; или &minus;
57
+ :hyphen => {
58
+ :insert => 0,
59
+ :length => 0
60
+ },
61
+ :acronym => 1, # выделять сокращения: 1 — выделять; 0 — не выделять
62
+ :symbols => 0, # как выводить типографированный текст: 0 — буквенными символами (&nbsp;); 1 — числовыми (&#160;)
63
+ # добавляет дополнительные атрибуты к ссылкам
64
+ :link => {
65
+ :target => '',
66
+ :class => ''
67
+ }
68
+ }
69
+ ```
70
+
71
+ ## Contributing
72
+
73
+ 1. Fork it
74
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
75
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
76
+ 4. Push to the branch (`git push origin my-new-feature`)
77
+ 5. Create new Pull Request
@@ -0,0 +1,7 @@
1
+ require "bundler/gem_tasks"
2
+
3
+ require 'rspec/core/rake_task'
4
+ desc "Run all examples"
5
+ RSpec::Core::RakeTask.new(:spec)
6
+
7
+ task :default => :spec
@@ -0,0 +1,8 @@
1
+ require "typograf/version"
2
+ require "typograf/client"
3
+
4
+ module Typograf
5
+ def self.process(text, options = {})
6
+ Client.new(options).send_request(text)
7
+ end
8
+ end
@@ -0,0 +1,136 @@
1
+ # encoding: utf-8
2
+ require 'net/http'
3
+
4
+ module Typograf
5
+ class NetworkError < StandardError
6
+ def initialize(message="", backtrace = nil)
7
+ super(message)
8
+ self.set_backtrace(backtrace) if backtrace
9
+ end
10
+ end
11
+
12
+ class Client
13
+ URL = 'http://www.typograf.ru/webservice/'
14
+ DEFAULT_PREFERENCES = {
15
+ :tags => 1, # 0 — не расставлять; 1 — расставлять
16
+ :tags_delete => 0, # 0 — не удалять; 1 — удалять до типографирования; 2 — удалять после типографирования
17
+ :paragraph => {
18
+ :insert => 1, # 1 — ставить; 0 — не ставить
19
+ # теги задают внешний вид обрамления параграфа, начальные и конечные теги соответственно (могут быть пустыми)
20
+ :start => '<p>',
21
+ :end => '</p>'
22
+ },
23
+ :newline => {
24
+ :tag => '<br />', # теги перевода строки.
25
+ :insert => 1 # перевод строки: 1 — ставить; 0 — не ставить
26
+ },
27
+ :cms_new_line => 0, # Переводы строк <p>&nbsp;</p>
28
+ :dos_text => 0, # удаляет одинарные переводы строк и переносы: 0 — не удалять; 1 — удалять
29
+ :nowraped => {
30
+ :insert => 1, # 1 — ставить; 0 — не ставить
31
+ :nonbsp => 0, # 0 — не использовать неразрывные конструкции вместо (неразрывного пробела); 1 — наоборот
32
+ :length => 0, # не объединять в неразрывные конструкции слова, написанные через дефис, с общей длинной больше N знаков. Если 0 то не используется
33
+ :start => '<nobr>',
34
+ :end => '</nobr>'
35
+ },
36
+ :hanging_punct => 0, # висячая пунктуация: 1 — использовать; 0 — не использовать
37
+ :hanging_line => 0, # висячие строки: 1 — удалять; 0 — не удалять
38
+ :minus_sign => '&ndash;', # указывает какой символ использовать вместо знака минус: — &ndash; или &minus;
39
+ :hyphen => {
40
+ :insert => 0,
41
+ :length => 0
42
+ },
43
+ :acronym => 1, # выделять сокращения: 1 — выделять; 0 — не выделять
44
+ :symbols => 0, # как выводить типографированный текст: 0 — буквенными символами (&nbsp;); 1 — числовыми (&#160;)
45
+ # добавляет дополнительные атрибуты к ссылкам
46
+ :link => {
47
+ :target => '',
48
+ :class => ''
49
+ }
50
+ }
51
+
52
+ def form_xml(options)
53
+ o = options
54
+ xml = <<-XML_TEMPLATE
55
+ <?xml version="1.0" encoding="windows-1251" ?>
56
+ <preferences>
57
+ <tags delete="#{o[:tags_delete]}">#{o[:tags]}</tags>
58
+ <paragraph insert="#{o[:paragraph][:insert]}">
59
+ <start><![CDATA[#{o[:paragraph][:start]}]]></start>
60
+ <end><![CDATA[#{o[:paragraph][:end]}]]></end>
61
+ </paragraph>
62
+ <newline insert="#{o[:newline][:insert]}"><![CDATA[#{o[:newline][:tag]}]]></newline>
63
+ <cmsNewLine valid="#{o[:cms_new_line]}" />
64
+ <dos-text delete="#{o[:dos_text]}" />
65
+ <nowraped insert="#{o[:nowraped][:insert]}" nonbsp="#{o[:nowraped][:nobsp]}" length="#{o[:nowraped][:length]}">
66
+ <start><![CDATA[#{o[:nowraped][:start]}]]></start>
67
+ <end><![CDATA[#{o[:nowraped][:end]}]]></end>
68
+ </nowraped>
69
+ <hanging-punct insert="#{o[:hanging_punct]}" />
70
+ <hanging-line delete="#{o[:hanging_line]}" />
71
+ <minus-sign><![CDATA[#{o[:minus_sign]}]]></minus-sign>
72
+ <hyphen insert="#{o[:hyphen][:insert]}" length="#{o[:hyphen][:length]}" />
73
+ <acronym insert="#{o[:acronym]}"></acronym>
74
+ <symbols type="#{o[:symbols]}" />
75
+ <link target="#{o[:link][:target]}" class="#{o[:link][:class]}" />
76
+ </preferences>
77
+ XML_TEMPLATE
78
+ xml.gsub(/^\s|\s$/, '')
79
+ end
80
+
81
+ def deep_merge(first, second)
82
+ target = first.dup
83
+ second.keys.each do |key|
84
+ if second[key].is_a?(Hash) && target[key].is_a?(Hash)
85
+ target[key] = deep_merge(target[key], second[key])
86
+ next
87
+ elsif second[key].is_a?(Hash) or target[key].is_a?(Hash)
88
+ raise ArgumentError, "Can't merge hashes"
89
+ end
90
+ target[key] = second[key]
91
+ end
92
+ target
93
+ end
94
+
95
+ def initialize(options = {})
96
+ @url = URI.parse(options.delete(:url) || URL)
97
+ # @chr = options.delete(:chr) || 'UTF-8'
98
+ @xml = if options.keys.length > 0
99
+ form_xml( deep_merge(DEFAULT_PREFERENCES, options) )
100
+ end
101
+ end
102
+
103
+ # Process text with remote web-service
104
+ def send_request(text)
105
+ params = {
106
+ 'text' => text.encode("cp1251"),
107
+ }
108
+ params['xml'] = @xml if @xml
109
+ # params['chr'] = @chr if @chr
110
+ params = URI.encode_www_form params
111
+ request = Net::HTTP::Post.new(@url.path + '?' + params)
112
+
113
+ begin
114
+ response = Net::HTTP.new(@url.host, @url.port).start do |http|
115
+ http.request(request)
116
+ end
117
+ rescue StandardError => exception
118
+ raise NetworkError.new(exception.message, exception.backtrace)
119
+ end
120
+
121
+ if !response.is_a?(Net::HTTPOK)
122
+ raise NetworkError, "#{response.code}: #{response.message}"
123
+ end
124
+
125
+ body = response.body.dup.force_encoding("cp1251")
126
+
127
+ # error = "\xCE\xF8\xE8\xE1\xEA\xE0: \xE2\xFB \xE7\xE0\xE1\xFB\xEB\xE8 \xEF\xE5\xF0\xE5\xE4\xE0\xF2\xFC \xF2\xE5\xEA\xF1\xF2"
128
+ # error.force_encoding("ASCII-8BIT") if error.respond_to?(:force_encoding)
129
+ if body == "Ошибка: вы забыли передать текст"
130
+ raise NetworkError, "Ошибка: вы забыли передать текст"
131
+ end
132
+
133
+ body.encode("utf-8").chomp
134
+ end
135
+ end
136
+ end
@@ -0,0 +1,3 @@
1
+ module Typograf
2
+ VERSION = "0.0.1"
3
+ end
@@ -0,0 +1,30 @@
1
+ # encoding: utf-8
2
+ require 'typograf'
3
+ require 'rspec'
4
+
5
+ describe Typograf do
6
+ it ".process" do
7
+ Typograf.process("- Это \"Типограф\"?\n— Нет, это «Типограф»!").should eq "<p>&mdash;&nbsp;Это &laquo;Типограф&raquo;?<br />\n&mdash;&nbsp;Нет, это &laquo;Типограф&raquo;!</p>"
8
+ end
9
+
10
+ it "should raise 404 error" do
11
+ lambda {Typograf.process("Тест", :url => 'http://www.typograf.ru/404')}.should raise_error Typograf::NetworkError
12
+ end
13
+
14
+ it "should raise host not found error" do
15
+ lambda {Typograf.process("Тест", :url => 'http://www')}.should raise_error Typograf::NetworkError
16
+ end
17
+
18
+ # TODO: mock server for offline testing, for detecting service change
19
+ # TODO: test every option
20
+ end
21
+
22
+ describe Typograf::Client do
23
+ it ".deep_merge" do
24
+ pending "TODO"
25
+ end
26
+
27
+ it ".form_xml" do
28
+ pending "TODO"
29
+ end
30
+ end
@@ -0,0 +1,23 @@
1
+ # -*- encoding: utf-8 -*-
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'typograf/version'
5
+
6
+ Gem::Specification.new do |gem|
7
+ gem.name = "typograf"
8
+ gem.version = Typograf::VERSION
9
+ gem.authors = ["stereobooster"]
10
+ gem.email = ["stereobooster@gmail.com"]
11
+ gem.description = %q{Universal tool for preparing russian text for web publishing. Ruby wrapper for typograf.ru webservice}
12
+ gem.summary = %q{Universal tool for preparing russian text for web publishing}
13
+ gem.homepage = "https://github.com/stereobooster/typograf"
14
+ gem.license = "MIT"
15
+
16
+ gem.files = `git ls-files`.split($/)
17
+ gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
18
+ gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
19
+ gem.require_paths = ["lib"]
20
+
21
+ gem.add_development_dependency "rake"
22
+ gem.add_development_dependency "rspec"
23
+ end
metadata ADDED
@@ -0,0 +1,96 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: typograf
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - stereobooster
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2012-12-04 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: rake
16
+ requirement: !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ! '>='
20
+ - !ruby/object:Gem::Version
21
+ version: '0'
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: '0'
30
+ - !ruby/object:Gem::Dependency
31
+ name: rspec
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: Universal tool for preparing russian text for web publishing. Ruby wrapper
47
+ for typograf.ru webservice
48
+ email:
49
+ - stereobooster@gmail.com
50
+ executables: []
51
+ extensions: []
52
+ extra_rdoc_files: []
53
+ files:
54
+ - .gitignore
55
+ - Gemfile
56
+ - LICENSE.txt
57
+ - README.md
58
+ - Rakefile
59
+ - lib/typograf.rb
60
+ - lib/typograf/client.rb
61
+ - lib/typograf/version.rb
62
+ - spec/typograf_spec.rb
63
+ - typograf.gemspec
64
+ homepage: https://github.com/stereobooster/typograf
65
+ licenses:
66
+ - MIT
67
+ post_install_message:
68
+ rdoc_options: []
69
+ require_paths:
70
+ - lib
71
+ required_ruby_version: !ruby/object:Gem::Requirement
72
+ none: false
73
+ requirements:
74
+ - - ! '>='
75
+ - !ruby/object:Gem::Version
76
+ version: '0'
77
+ segments:
78
+ - 0
79
+ hash: -1019651219
80
+ required_rubygems_version: !ruby/object:Gem::Requirement
81
+ none: false
82
+ requirements:
83
+ - - ! '>='
84
+ - !ruby/object:Gem::Version
85
+ version: '0'
86
+ segments:
87
+ - 0
88
+ hash: -1019651219
89
+ requirements: []
90
+ rubyforge_project:
91
+ rubygems_version: 1.8.24
92
+ signing_key:
93
+ specification_version: 3
94
+ summary: Universal tool for preparing russian text for web publishing
95
+ test_files:
96
+ - spec/typograf_spec.rb