Class: TypographerHelper::Parsers::WrapFirstLetter

Inherits:
Object
  • Object
show all
Defined in:
lib/typographer-addons/wrap_first_letter.rb

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ WrapFirstLetter

Returns a new instance of WrapFirstLetter.



5
6
7
8
9
# File 'lib/typographer-addons/wrap_first_letter.rb', line 5

def initialize(options = {})
  @options = options
  @options[:text] ||= Proc.new { |letter| '<span class="first_letter">'+letter+'</span>'}
  @options[:matcher] ||= 'p:first'
end

Instance Method Details

#parse(string) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/typographer-addons/wrap_first_letter.rb', line 11

def parse(string)
  doc = Nokogiri.HTML string
  target = doc.css(@options[:matcher]).first
  text = target.inner_html

  unless text.blank?
    match = /(<([^>]+)>|\s)*(.)/.match text
    new_text_part = @options[:text].call(match[3])
    target.inner_html = text[0...match.offset(3)[0]] + new_text_part + text[match.offset(3)[1]...text.length]
  end

  doc.search('body').children.to_xhtml
end