require 'rubygems'
require 'hpricot'
require 'open-uri'
require 'ostruct'
class XFN
class InvalidRelationship < StandardError; end
class Link < OpenStruct
def to_html
"<a href=\"#{link}\" rel=\"#{relation.join(' ')}\">#{name}</a>"
end
def ==(link)
(self.name == link.name) & (self.link == link.link) & (self.relation = link.relation)
end
end
attr_accessor :links
def initialize(uri)
doc = Hpricot open(uri)
relinks = doc/"a[@rel]"
@links = relinks.map { |rl| Link.new(:name=>rl.innerHTML, :link=>rl[:href], :relation=>rl[:rel].split(/\s+/)) }
end
def [](*r)
rels = r.map { |rel| self.send(rel.to_sym) }
rels.inject() {|matched_rels,array| matched_rels & array }
end
def method_missing(method, *args, &block)
return @links.select{ |link| link.relation.include? method.to_s }
end
end
if $0 == __FILE__
require "test/unit"
class TestXFN < Test::Unit::TestCase
def setup
@xfn = XFN.new('test_data.html')
end
def test_method_missing
assert_equal [], @xfn.googlyeyes
end
def test_initialize
xfn = XFN.allocate
assert_nil xfn.links
assert_not_nil @xfn.links
end
def test_array_accessor
assert_equal @xfn['met','contact'], XFN::Link.new( :name => "contact + met", :link =>"#contact", :relation => ["contact", "met"])
end
end
end
## error:
RubyMate r5712 running Ruby v1.8.5 (/usr/local/bin/ruby)
>>> xfn.rb
Loaded suite /Users/cdcarter/software/xfn
Started
E
.
.
Finished in 0.081772 seconds.
1) Error:
test_array_accessor(TestXFN):
NoMethodError: undefined method `name' for 10138210:Fixnum
method == in xfn.rb at line 14
method include? in ostruct.rb at line 115
method inspect in ostruct.rb at line 115
method pretty_print in pp.rb at line 259
method pp in pp.rb at line 140
method group in prettyprint.rb at line 201
method nest in prettyprint.rb at line 227
method group in prettyprint.rb at line 200
method group_sub in prettyprint.rb at line 212
method group in prettyprint.rb at line 199
method pp in pp.rb at line 140
method pretty_print in pp.rb at line 304
method seplist in pp.rb at line 201
method each in pp.rb at line 195
method __send__ in pp.rb at line 195
method seplist in pp.rb at line 195
method pretty_print in pp.rb at line 303
method group in prettyprint.rb at line 201
method nest in prettyprint.rb at line 227
method group in prettyprint.rb at line 200
method group_sub in prettyprint.rb at line 212
method group in prettyprint.rb at line 199
method pretty_print in pp.rb at line 302
method pp in pp.rb at line 140
method group in prettyprint.rb at line 201
method nest in prettyprint.rb at line 227
method group in prettyprint.rb at line 200
method group_sub in prettyprint.rb at line 212
method group in prettyprint.rb at line 199
method pp in pp.rb at line 140
method pp in pp.rb at line 77
method guard_inspect_key in pp.rb at line 119
method pp in pp.rb at line 77
method test_array_accessor in xfn.rb at line 56
3 tests, 4 assertions, 0 failures, 1 errors