Class: Linky

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

Class Method Summary collapse

Class Method Details

Link a keyword to a target within some HTML.

* keyword: what you want linked
* target: where you want it linked to
* html: the html you want to look for the keyword in, or Nokogiri::HTML::DocumentFragment object.
* options: any extra attributes (besides href) that you want on the link.

Here’s an example:

require 'linky'
html = "<p>link all occurances of the word "more."</p><div>some more text</div>"
Linky.link "more", "http://more.com", html, :class => "linky"
# returns "<p>link the word "<a href="http://more.com" class="linky">more</a>."</p><div>some <a href="http://more.com" class="linky">more</a> text</div>"

if you provide parameter html as DocumentFragment object, after calling link(), that object is updated as well. Means the output of link(keyword, target, html) == html.to_xhtml



18
19
20
21
22
23
24
25
26
27
# File 'lib/linky/linky.rb', line 18

def link(keyword, target, html, options={})
  options = options.map {|k,v| %{#{k}="#{v}"}}.join " " 
  block = proc {|keyword| %{<a href="#{target}" #{options}>#{keyword}</a>}}
  html_fragment = html.kind_of?(Nokogiri::HTML::DocumentFragment) ? html : Nokogiri::HTML::DocumentFragment.parse(html)
  html_fragment_orig = html_fragment.dup

  real_link keyword.to_s, html_fragment, &block
  raise "We lost some content in attempting to link it. Please report a bug" unless html_fragment.text == html_fragment_orig.text 
  html_fragment.to_xhtml
end