Class: TypographyHelper::Core

Inherits:
Object
  • Object
show all
Defined in:
lib/typography/core.rb

Instance Method Summary collapse

Constructor Details

#initialize(str, options = {}) ⇒ Core

Returns a new instance of Core.



4
5
6
7
8
# File 'lib/typography/core.rb', line 4

def initialize(str, options = {})
  @source  = str
  @out     = str.dup
  @options = options.merge({})
end

Instance Method Details

#replace_quotes(left1 = '“', right1 = '”', left2 = '‘', right2 = '’', letters = 'a-zA-Z') ⇒ Object

def replace_quotes!(*args)

  @source.replace self.replace_quotes(*args)
end


45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/typography/core.rb', line 45

def replace_quotes(left1 = '“', right1 = '”', left2 = '‘', right2 = '’', letters = 'a-zA-Z')
  str = @out.dup

  replace_quotes = lambda do
    old_str = str.dup
    str.gsub!(Regexp.new("(\"|\'|")([#{letters}].*?[^\\s])\\1", Regexp::MULTILINE | Regexp::IGNORECASE)) do |match|
      inside, before, after = $2, $`, $'
      if after.match(/^([^<]+>|>)/) || before.match(/<[^>]+$/) #inside tag
        match
      else
        "#{left1}#{inside}#{right1}"
      end
    end
    old_str != str
  end
  while replace_quotes.call do end

  # second level
  replace_second_level_quotes = lambda do
    str.gsub! Regexp.new("#{left1}(.*)#{left1}(.*)#{right1}(.*)#{right1}", Regexp::MULTILINE | Regexp::IGNORECASE) do |match|
      "#{left1}#{$1}#{left2}#{$2}#{right2}#{$3}#{right1}"
    end
  end
  while replace_second_level_quotes.call do end

  str
end

#typographyObject



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/typography/core.rb', line 10

def typography
  #apostrophe
  @out.gsub!(/(\w)'(\w)/, '\1&#146;\2')
  @out.gsub!(/\“/,'&#132;')
  @out.gsub!(/\”/,'&#147;')
  #russian quotes
  @out = replace_quotes '&laquo;', '&raquo;', '&#132;', '&#147;', 'а-яА-Я'

  #english quotes
  @out = replace_quotes

  #mdash
  @out.gsub!(/--/, '&mdash;')
  @out.gsub!(/(\w|;|,)\s+(—|–|-)\s*(\w)/, '\1&nbsp;&mdash; \3')
  @out.gsub!(/\s+&mdash;/, '&nbsp;&mdash;')

  #nobr
  #around dash-separated words (что-то)
  @out.gsub!(/(^|\s)((\w|0-9){1,3})-((\w|0-9){1,3})($|\s)/, '\1<span class="nobr">\2-\4</span>\6')
  #1980-x почему-то
  @out.gsub!(/(^|\s)((\w|0-9)+)-((\w|0-9){1,3})($|\s)/, '\1<span class="nobr">\2-\4</span>\6')

  #non brake space
  @out.gsub!(/(^|\s|\()(\w{1,2})\s+([^\s])/i, '\1\2&nbsp;\3')
  @out.gsub!(/(^|\s|\()&([A-Za-z0-9]{2,8}|#[\d]*);(\w{1,2})\s+([^\s])/i, '\1&\2;\3&nbsp;\4') #entities
  @out.gsub!(/(&nbsp;|&#161;)(\w{1,2})\s+([^\s])/i, '\1\2&nbsp;\3\4')

  @out
end