Skip to content

Instantly share code, notes, and snippets.

@brynary
Created December 18, 2008 07:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brynary/37427 to your computer and use it in GitHub Desktop.
Save brynary/37427 to your computer and use it in GitHub Desktop.
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
require "nokogiri"
class HTMLTransformer
def initialize(xpath, &block)
@xpath = xpath
@block = block
end
def transform(html)
doc = Nokogiri::HTML(html)
body = doc.at("/html/body")
body.xpath(@xpath).each do |node|
@block.call(node)
end
body.inner_html
end
end
class PrivateProfileLinkDecorator
def self.decorate(html)
transformer = HTMLTransformer.new(xpath) do |node|
add_rel_attribute(node)
end
transformer.transform(html)
end
def self.add_rel_attribute(node)
node.set_attribute("rel", "jsfacebox.private_profile_dialog")
end
def self.xpath
"//a[contains(@class, 'user_link')]"
end
end
describe PrivateProfileLinkDecorator do
it "should not modify non-links" do
html = "<p>Hi</p>"
PrivateProfileLinkDecorator.decorate(html).should == html
end
it "should not modify links without the user_link class" do
html = "<a>link</a>"
PrivateProfileLinkDecorator.decorate(html).should == html
end
it "should modify links" do
html = "<a class='user_link'>link</a>"
PrivateProfileLinkDecorator.decorate(html).should ==
"<a class=\"user_link\" rel=\"jsfacebox.private_profile_dialog\">link</a>"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment